2011-07-18 177 views
0

我正在编写一个课程程序,用于分析输入的不同产品代码。这很简单,但我有一个问题。如果用户输入“E”或“e”,我试图结束一个循环。但是,它并没有结束循环。这是在while语句的结尾,因此将loop设置为false应该结束它,它甚至不会输出总数,所以我已经搞砸了。代码是一个字符串类型。字符串问题 - Java

 // Prompt the user for another company code or exit 
     System.out.print("Enter the company code or type 'e' to exit: "); 

     // Input the user's company code 
     code = scan.nextLine(); 

     // Check to see if the user wants to exit 
     if (code == "e" || code == "E") { 
      // Output final statistics 
      System.out.print("Total valid codes: " + valid + "/n"); 
      System.out.print("Total banned codes: " + banned); 

      // End the loop  
      loop = false; 
     } 

任何想法?谢谢!

+0

我看不到任何代码回路? –

+0

你可以放入循环码吗?我想你想用“打破”而是结束循环,但我不知道你的循环是什么样的。 – MacGyver

回答

6

您需要使用code.equals("e") || code.equals("E")(或者只是code.equalsIgnoreCase("e"))。这是因为==确实身份比较(“是Xÿ相同的对象?”),而equals确实比较(“做Xÿ具有相同的价值?”) 。

+0

非常感谢你和所有回答的人。 –

+0

作为一个后续问题,我采用TRV2475A5R-14并创建一个只有2475的字符数组。我需要确保它只包含数字字符。你如何推荐我这样做? –

+0

@Brooks:你应该在网站上提出一个新的问题。但是,这里有一个单行的答案:'code.matches(“\\ d +”)'。 –

1

使用.equals()没有==

1

比较字符串通过equals==

if (code.equals("e") || code.equals("E")) { 
1

使用.equals进行比较时,字符串比较字符串。

你的情况,你甚至可以用

if (code.equalsIgnoreCase("e")) { 

的原因是==检查是否两个对象是同一个对象。你可以有两个不同的字符串对象表示相同的字符串。

1

使用.equalsIgnoreCase("e"),==比较内存中对象的地址和.equals(String)区分大小写。

1

试试这个:

** LOOP * {

// Prompt the user for another company code or exit 
    System.out.print("Enter the company code or type 'e' to exit: "); 

    // Input the user's company code 
    code = scan.nextLine(); 

    // Check to see if the user wants to exit 
    if (code.equals("e") || code.equals("E")) { // <====== see new code 
     // Output final statistics 
     System.out.print("Total valid codes: " + valid + "/n"); 
     System.out.print("Total banned codes: " + banned); 

     // End the loop  
     //loop = false; 
     break; // <====== see new code 
    } 

}

4

当比较Strings你应该始终使用equals方法而不是==,所以

if ("e".equals(code) || "E".equals(code)) 

可能是你想要的。

原因是Strings是Java中的特殊对象。它们是不可变的,它们可以被实现以优化存储器使用。常量(例如代码中的“e”和“E”)由编译器自动执行,但scanLine方法可能会返回非实际字符串,因此==比较将失败。

记住,当我们谈论的对象,==检查参考平等值相等,即a == b的意思是“做ab指向同一个对象吗?”。有可能a.equals(b)为真,但a == b为假。

+0

+1为谈论实习;我目前正在撰写一些幻灯片,而我所谈论的主题之一是具有同等价值的不可变对象如何合并和/或实现。 :-D –

2

使用equalsIgnoreCase()

您的代码将是

if (code.equalsIgnoreCase("e")) { 
      // Output final statistics 
      System.out.print("Total valid codes: " + valid + "/n"); 
      System.out.print("Total banned codes: " + banned); 

      // End the loop  
      loop = false; 
     } 
0

我想说的东西像代码它能够更好地使用Java枚举。使用枚举可以使用==运算符进行比较。

0

这是更好地使用

code.equalsIgnoreCase("e") 
0

使用https://stackoverflow.com/a/513839/1394464

== tests for reference equality. 

.equals() tests for value equality. 

因此给出的解释,如果你真的想测试两个字符串是否有你应该使用.equals相同的值()而不是==。

所以

if(code == "e" || code == "E") 

应该成为

if(code.equals("e") || code.equals("E"))