2013-11-24 191 views
0
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();捕捉字符串。输出如下:Java虽然循环将不会循环

[ 

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循环重复。谢谢您的帮助!

+0

当你比较字符串时,你必须使用equals()。 – Sajmon

+0

工作过的很棒!谢谢您的帮助! – Ixen

回答

8

比较字符串与==.equals代替

while(cont.equals("Yes") || cont.equals("yes")) 

甚至更​​好:

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

添加提示:使用.equalsIgnoreCase() – ljgw

+0

@ljgw好主意,我会添加它。 – Octoshape

1

您需要需要将Strings这种方式比较:

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

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

0

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

0

变化这个

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

变化

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

由于

while(cont.equalsIgnoreCase("Yes")) 

原因

你需要知道背后==的原因和equals()

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()