我有一个错误,上面写着语法错误插入“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);
}
}
}
}
答案 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