如何正确使用OR运算符java

时间:2015-02-19 12:27:43

标签: java

嗨,我已经把头发拉过来了

如果用户输入0或运行总数= 20,我希望此程序终止。当我尝试编译时,我收到一个错误:

这是我的代码 - 我做错了什么?

import java.util.Scanner;

public class RunningTotal
{  
       public static void main( String[] args)
       {   
            Scanner keyboard = new Scanner(System.in);  

            int current = 1, total = 0;

            System.out.print( "Type in a bunch of values and I'll add them up. ");
            System.out.println( "I'll stop when you type a zero." );

            do
            {
                System.out.print("Value: ");
                current = keyboard.nextInt();
                int newtotal = current + total;
                total = newtotal;
                System.out.println("The total so far is: " + total);
            }  while (current != 0) || (total != 20);

            System.out.println("The final total is: " + total);
        }
}       

3 个答案:

答案 0 :(得分:2)

错误地放置括号时出现错误

您必须使用AND而不是OR

do
{
    System.out.print("Value: ");
    current = keyboard.nextInt();
    int newtotal = current + total;
    total = newtotal;
    System.out.println("The total so far is: " + total);
}  while ((current != 0) && (total != 20));

答案 1 :(得分:0)

你的while循环缺少一个额外的()来包装OR条件(每个条件都需要在括号中)

public class RunningTotal
{  
   public static void main( String[] args)
   {   
        Scanner keyboard = new Scanner(System.in);  

        int current = 1, total = 0;

        System.out.print( "Type in a bunch of values and I'll add them up.     ");
        System.out.println( "I'll stop when you type a zero." );

        do
        {
            System.out.print("Value: ");
            current = keyboard.nextInt();
            int newtotal = current + total;
            total = newtotal;
            System.out.println("The total so far is: " + total);
        }  while ((current != 0) || (total != 20));

        System.out.println("The final total is: " + total);
    }

}

答案 2 :(得分:0)

你的while行是错误的应该是这样的,while中的表达式必须在braces()中像这样while(expression);而不是像while(表达式)||(expresion); 如果你真的想使用或者这个解决方案

 boolean notFinished = true;
     do
                {
                    System.out.print("Value: ");
                    current = keyboard.nextInt();
                    int newtotal = current + total;
                    total = newtotal;
                    System.out.println("The total so far is: " + total);
                    if (current==0 || total ==20){
 notFinished=false;
                    }
                }  while (notFinished);

这是一个更简单的解决方案,由于de Morgans Law,这也是正确的

 while ((current != 0) && (total != 20));

此行也应该有效

while(current !=0 && total !=20);