2014-09-25 120 views
1

真的是新來的java和這個任務有一些麻煩。該任務是:簡單的Java計算器 - while循環直到答案爲0

編寫打印歡迎 消息的簡單的計算器程序,接受來自用戶的簡單的算術表達式,並且執行 所請求的操作。你的程序應該重複這個 ,直到兩個操作數爲0,然後退出。

它運行良好,但我不知道如何得到While循環的句柄,以便計算器將繼續,直到答案爲0.對不起,如果這是一個非常基本的問題。任何幫助,將不勝感激。

import java.util.Scanner; 

class Calculator{ 
    public static void main(String[] args) 
    { 
     System.out.println("Welcome to CSC 210 Calculator by Bob the Builder!"); 
     System.out.println("Enter an integer operation: "); 

    Scanner input = new Scanner(System.in); 

     int x = input.nextInt(); 
     String operation= input.next(); 
     int y = input.nextInt(); 

      while(x + y != 0){ 

     if(operation.equals("+")){ 
      System.out.println(x + y); 
     } 

     else if(operation.equals("-")){ 
      System.out.println(x - y); 
     } 

     else if(operation.equals("*")){ 
      System.out.println(x * y); 
     } 

     else if(operation.equals("/")){ 
      System.out.println(x/y); 
     } 

     else if(operation.equals("%")){ 
      System.out.println(x % y + y); 
     } 


     else { 
      System.out.println("Operation is invalid."); 
     } 


       System.out.println("Enter an integer operation: "); 
       if(x + y != 0); 
           break; 
     } 

    } 
} 
+0

你可以做的是=假'並運行你的代碼,直到'flag'爲false。一旦操作爲'= 0',將您的標誌設置爲true。 – smr5 2014-09-25 00:42:13

回答

-1

解決上述問題。

編寫一個簡單的計算器程序,打印歡迎消息,接受來自用戶的簡單算術表達式,並執行請求的操作。你的程序應該重複這個操作,直到兩個操作數爲0,然後退出。

你要多注意以下提示:「X + Y = 0」

  1. 「直到兩個操作數爲0」,所以你可以循環出的條件,例如,x = 5,y = -5,你不能循環。
  2. 「repeat」表示您應該在while循環中將新的int值賦給x和y變量。

這裏的代碼,可以幫助你

import java.util.Scanner; 

class Calculator{ 

    public static void main(String[] args){ 
     System.out.println("Welcome to CSC 210 Calculator by Bob the Builder!"); 
     System.out.println("Enter an integer operation: "); 

     Scanner input = new Scanner(System.in); 

     int x = input.nextInt(); 
     String operation= input.next(); 
     int y = input.nextInt(); 

     while(x != 0 && y != 0){ 

      if(operation.equals("+")){ 
       System.out.println(x + y); 
      } 
      else if(operation.equals("-")){ 
       System.out.println(x - y); 
      } 

      else if(operation.equals("*")){ 
       System.out.println(x * y); 
      } 

      else if(operation.equals("/")){ 
       System.out.println(x/y); 
      } 

      else if(operation.equals("%")){ 
       System.out.println(x % y + y); 
      } 
      else { 
       System.out.println("Operation is invalid."); 
      } 
      System.out.println("Enter an integer operation: "); 

      x = input.nextInt(); 
      y = input.nextInt(); 
     } 

    } 
} 
+0

add'operation = input.next();'在while循環中。 – triffic 2014-09-25 01:51:51

0

使用開關的情況下代替創建一個'布爾標誌,如果else語句

if(a !=0 && b!=0) 
{ 
switch(ch)//ch is where you stored the operator 
{ 

case '-': System.out.println(a - b); 
break; 
case ' +':System.out.println(a+b);break; 
} 
else 
{ 
System.out.println("Enter an integer operation: ");}