Java While循环不会循环

时间:2013-11-24 19:40:42

标签: java loops while-loop calculator

package pack;

import java.util.Scanner;

public class Calculator {


    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        String cont = "Yes";

        while(cont == "Yes" || cont == "yes" ){
            System.out.print("Enter a Number: ");
            int x = scan.nextInt();
            System.out.print("Enter another Number: ");
            int y = scan.nextInt();

            int diff = x - y;
            int sum = x + y;
            int prod = x * y;
            int quot = x / y;

            System.out.println("The Sum is: " + sum);
            System.out.println("The Diffrence is: " + diff);
            System.out.println("The Product is: " + prod);
            System.out.println("The quotient is: " + quot);

            System.out.print("Enter Yes to Continue: ");
            cont = scan.next();
            System.out.println(cont);

        }

    }



}

这整个代码都有效,但while循环不重复。 cont = scan.next();正在捕捉字符串。输出如下:

[

Enter a Number: 5

Enter another Number: 6

The Sum is: 11

The Diffrence is: -1

The Product is: 30

The quotient is: 0

Enter Yes to Continue: Yes

Yes

]

然后程序终止没有任何问题。所有我需要它来重复while循环。谢谢你的帮助!

5 个答案:

答案 0 :(得分:8)

将字符串与.equals而非==

进行比较
while(cont.equals("Yes") || cont.equals("yes") )

甚至更好:

while(cont.equalsIgnoreCase("Yes"))

答案 1 :(得分:1)

您需要以这种方式比较Strings

while("Yes".equalsIgnoreCase(cont))...

这是因为在使用输入时,您不会有String 文字,而是String 对象。这些需要通过equals()而非==进行比较。

答案 2 :(得分:1)

更改

while(cont == "Yes" || cont == "yes" ){

作为

while(cont.equalsIgnoreCase("Yes"))

原因

您需要了解==equals()

背后的原因 {p} equals()类中存在

java.lang.Object方法,并且需要检查对象状态的等效性!这意味着,对象的内容。期望==运算符检查实际对象实例是否相同。

if语句

的示例

考虑两个不同的参考变量str1str2

str1 = new String("abc");
str2 = new String("abc");

如果您使用equals()

System.out.println((str1.equals(str2))?"TRUE":"FALSE");

您将获得TRUE

的输出

如果您使用==

 System.out.println((str1==str2)?"TRUE":"FALSE");

现在您将获得FALSE作为输出,因为str1str2都指向两个不同的对象,即使它们都共享相同的字符串内容。这是因为new String()每次创建一个新对象。

答案 3 :(得分:0)

而不是(cont ==“是”|| cont ==“是”)你应该使用(cont.equals(“Yes”)|| cont.equals(“Yes”))

答案 4 :(得分:0)

更改为

 while(cont.equalsIgnoreCase("Yes"))