语法错误插入表达式以完成块语句JAVA

时间:2014-12-17 14:35:53

标签: java

到目前为止,这是我的代码,用于创建一个程序,该程序接受用户输入的1到100之间的数字,只有偶数。它还需要在输入N或n时结束,并计算有效数字的总和以及显示最高数字。

我有一个错误,上面写着语法错误插入“while(表达式)”;完成这段代码的块语句......:

'System.out.println(“输入整数列表,按N或n将计算你的数字”);'

任何帮助将不胜感激。

  • 这是代码的开头: -
package week11;
import java.util.*;
public class repeatlist {

public static void main(String args[]){

        Scanner sc = new Scanner(System.in);
        int number = 0, Sum = 0; //variables
        char letter;
        char choice;

        //if (Number %2 ==0)
        {
        do

            System.out.println("Enter the list of whole numbers, pressing N or n will Calculate your numbers");
            number = sc.nextInt();
            letter = sc.next().charAt(0);


            {
                 while(letter != 'N' && letter != 'n' ); 
                    System.out.println("end of program");

                Sum = Sum + number;
                number = sc.nextInt(); 

            System.out.println("Sum is "+ Sum);
            System.out.print("Do you want to repeat the ");
            System.out.println("  Program ['Y' or 'N']");
            choice = sc.next().charAt(0);
            }
        }
}

}

2 个答案:

答案 0 :(得分:1)

试试这个

    do {
        System.out.println("Enter the list of whole numbers, pressing N or n will Calculate your numbers");
        number = sc.nextInt();
        letter = sc.next().charAt(0);
    } 
    while (letter != 'N' && letter != 'n' ); 
    System.out.println("end of program");

    Sum = Sum + number;
    number = sc.nextInt(); 

    System.out.println("Sum is "+ Sum);
    System.out.print("Do you want to repeat the ");
    System.out.println("  Program ['Y' or 'N']");
    choice = sc.next().charAt(0);

尽量保持代码格式良好,所有IDE都可以选择为您格式化。它会帮助你发现这种

答案 1 :(得分:1)

缩进为何如此重要的一个很好的例子。您当前的循环基本上执行以下操作:

{
    do System.out.println("Enter the list of whole numbers, pressing N or n will Calculate your numbers");

    //Rest of your first code block 

    {
        while (letter != 'N' && letter != 'n'); //Does nothing

        //Your second code block
    }
}

许多不必要的括号和语句会导致代码无法按预期运行。

也许您正在寻找

do {
    //Your first code block
    //Your second code block
} while (letter != 'N' && letter != 'n' );

do {
    //Your first code block
} while (letter != 'N' && letter != 'n' );
//Your second code block