所以我在我的类文件的构造函数中乱搞了String数据类型,虽然一切都正确编译,但是当我运行应用程序文件时,程序并没有给出所需的结果。我保持简短,看看它是否可行,所以我的类文件如下:
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);
}
我的申请文件如下:
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();
}
}
我做错了什么?我是否使用错误的方法来解析扫描仪中的信息?或者我错误地使用equalsIgnoreCase?这是我实施这些方法的第一次尝试,所以我可能会为所有我知道的方式而烦恼。当我运行应用程序类时,我的结果是跟踪else子句的结果,或者,"我们不带这些品牌"或者"我们没有携带那种颜色"。然后,在我的显示语句中,变量名称被替换为" null"。这一切都是为了练习,所以任何见解都会很棒。谢谢!
答案 0 :(得分:3)
应该翻转传递给构造函数的参数。
在您的申请中:
Guitar1 = new StringPractice(brand, color);
但在您的代码中:
public StringPractice(String clor, String brnd) {