2013-11-24 190 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()