嘿,伙计我在if语句中遇到了我的代码问题。无论我输入什么,if语句总是将f_resist []返回到0.我认为if语句中有错误,但我不确定:(
Scanner u_scancolor = new Scanner(System.in); //declare input box
System.out.println("Enter three colors on the resistor seperated by hyphens. ie: Red-Blue-Brown");
System.out.println("Colours you can use: Black, Brown, Red, White, Orange, Yellow, Green, Grey, Violet, Blue");
String f_wire = u_scancolor.next(); //takes a string
System.out.println(f_wire);
int [] f_resist;
f_resist = new int [3];
String [] f_wordcolor= f_wire.split("-"); //splits the colors by hyphen into individual strings
for (int cnt1=0 ; cnt1<3; cnt1++) {
f_wordcolor [cnt1] = f_wordcolor [cnt1].toUpperCase();
System.out.println(f_wordcolor [cnt1]);
if (f_wordcolor [cnt1] == "BLACK ") {
f_resist [cnt1] = 0;
}
else if (f_wordcolor [cnt1] == "BROWN") {
f_resist [cnt1] = 1;
}
else if (f_wordcolor [cnt1] == "RED") {
f_resist [cnt1] = 2;
}
else if (f_wordcolor [cnt1] == "ORANGE") {
f_resist [cnt1] = 3;
}
else if (f_wordcolor [cnt1] == "YELLOW") {
f_resist [cnt1] = 4;
}
else if (f_wordcolor [cnt1] == "GREEN") {
f_resist [cnt1] = 5;
}
else if (f_wordcolor [cnt1] == "BLUE") {
f_resist [cnt1] = 6;
}
else if (f_wordcolor [cnt1] == "VIOLET") {
f_resist [cnt1] = 7;
}
else if (f_wordcolor [cnt1] == "GREY") {
f_resist [cnt1] = 8;
}
else if (f_wordcolor [cnt1] == "WHITE") {
f_resist [cnt1] = 9;
}
System.out.println(f_resist [cnt1]);
}
String f_add1 = Integer.toString(f_resist [0]);
String f_add2 = Integer.toString(f_resist [1]);
String f_stringadd = f_add1 + f_add2;
int f_intadd = Integer.parseInt(f_stringadd);
int f_ohm = f_intadd*10^f_resist[2];
System.out.println("Total ohms: " + f_ohm);
}
}
答案 0 :(得分:1)
您无法使用==
比较字符串,但必须使用String.equals
方法。因此,您使用f_wordcolor[cnt1].equals("BLACK")
之类的内容。
但更好的是,使用HashMap
来包含映射,而不是if / elses的巨大嵌套:
private static final Map<String, Integer> COLORMAP = new HashMap<>();
static {
COLORMAP.put("BLACK", 0);
COLORMAP.put("BROWN", 1);
COLORMAP.put("RED", 2);
COLORMAP.put("ORANGE", 3);
COLORMAP.put("YELLOW", 4);
COLORMAP.put("GREEN", 5);
COLORMAP.put("BLUE", 6);
COLORMAP.put("VIOLET", 7);
COLORMAP.put("GREY", 8);
COLORMAP.put("WHITE", 9);
}
/* ... */
f_resist[cnt1] = COLORMAP.get(f_wordcolor[cnt1]);
答案 1 :(得分:0)
要比较两个字符串,您必须使用 equals 方法。 示例:
String ex ="foo";
if(ex.equals("foo")){
System.out.println("The string is equals to foo")
}
无论如何,请考虑使用开关构造