gpt4 book ai didi

java - 数组 If 语句问题

转载 作者:行者123 更新时间:2023-12-01 10:22:03 25 4
gpt4 key购买 nike

嘿伙计们,我在 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);
}
}

最佳答案

您不能使用 == 比较字符串,而必须使用 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]);

关于java - 数组 If 语句问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35530654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com