2014-09-25 124 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: ");}