【问题标题】:Array If Statement Trouble [duplicate]数组If语句麻烦[重复]
【发布时间】:2016-02-21 00:07:06
【问题描述】:

大家好,我在 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);
 }
}

【问题讨论】:

  • 请注意..您在“BLACK”中有一个额外的空间

标签: java arrays if-statement


【解决方案1】:

您不能使用== 比较字符串,而必须使用String.equals 方法。所以你会使用f_wordcolor[cnt1].equals("BLACK")之类的东西。

但更好的是,使用 HashMap 来包含映射,而不是 if/else 的巨大巢穴:

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]);

【讨论】:

    【解决方案2】:

    要比较两个字符串,您必须使用 equals 方法。 示例:

    String ex ="foo";
    if(ex.equals("foo")){
    System.out.println("The string is equals to foo")
    }
    

    无论如何考虑使用 switch 构造

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多