如何正确使用OR运算符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);
        }
}       

您在中错误地放置了括号

在这里,您必须使用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));

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);
    }

}

while行错误,应该是这样的while中的表达式必须像while(expression)一样用大括号();不喜欢while(expression)||(expression);如果你真的想使用或这是一个解决方案

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

这是一个更简单的解决方案,这也是正确的,因为德摩根定律

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

这条线路也应该可以

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

最新更新