Domanda

So i've been messing around with String data types in the constructor of my class file, and while everything compiles correctly, when I run the application file, the program doesn't give the desired result. I kept it short to see if it would work, so my class file is as follows:

  public class StringPractice
{
   private String color;
   private String brand;

   public StringPractice() {

   String color = "";
   String brand = "";
   }

   public StringPractice(String clor, String brnd) {

   setColor(clor);
   setBrand(brnd);
   }

   public void setColor(String clor) {

         if (clor.equalsIgnoreCase("Red")) {
               color = clor;
         }
         else {
         System.out.println("We dont't carry that color");
         } 
   }

   public void setBrand(String brnd) {

         if (brnd.equalsIgnoreCase("Gibson")) {
               brand = brnd;
         }
         else {
               System.out.println("We do not carry that brand");
         }
   }

   public String getColor() {
         return color;
   }

   public String getBrand() {
         return brand;
   }

   public void display() {
         System.out.println("Our brands are: " + brand + "Our colors are: " + color); 


   }

My application file is as follows:

import java.util.Scanner;

public class UseStringPractice
{
   public static void main(String[] args)
   {

   String brand = "";
   String color = "";

   Scanner keyboard = new Scanner(System.in);

   StringPractice Guitar1;

   System.out.println("Please enter the brand you would like");
   brand = keyboard.next();

   System.out.println("Please enter the color you would like");
   color = keyboard.next();

   Guitar1 = new StringPractice(brand, color);
   Guitar1.display();

   }

}   

What am I doing incorrectly? Am I using the wrong methods to parse the information from scanner? Or am I using equalsIgnoreCase incorrectly? This is my first attempt at implementing these methods, so I may be wayyy off for all I know. When I run the application class, my result is that of the trailing else clause, or, "We do not carry those brands" or "We don't carry that color". Then, in my display statement, the variable names are replaced with "null". This is all for practice so any insight would be fantastic. Thanks!

È stato utile?

Soluzione

Your arguments being passed to your constructor should be flipped.

In your application:

Guitar1 = new StringPractice(brand, color);

but in your code:

public StringPractice(String clor, String brnd) {
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top