Java 循环结束后,循环内设置的值是否丢失?
我正在学习一门名为“Java面向对象编程”的在线课程 我不明白 创建一个程序,要求用户输入数字(整数)。程序打印“键入数字”,直到用户键入数字-1。当用户键入数字-1时,程序打印“谢谢,待会儿见!”!以及用户输入的数字的总和(不包括数字-1)Java 循环结束后,循环内设置的值是否丢失?,java,Java,我正在学习一门名为“Java面向对象编程”的在线课程 我不明白 创建一个程序,要求用户输入数字(整数)。程序打印“键入数字”,直到用户键入数字-1。当用户键入数字-1时,程序打印“谢谢,待会儿见!”!以及用户输入的数字的总和(不包括数字-1) import java.util.Scanner; 公共类循环发送{ 公共静态void main(字符串[]args){ 扫描仪阅读器=新扫描仪(System.in); int n=0; 整数和=0; 而(n!=-1){ 系统输出打印项次(“类型编号”);
import java.util.Scanner;
公共类循环发送{
公共静态void main(字符串[]args){
扫描仪阅读器=新扫描仪(System.in);
int n=0;
整数和=0;
而(n!=-1){
系统输出打印项次(“类型编号”);
n=Integer.parseInt(reader.nextLine());
sum=sum+n;//将while循环更改为检查用户输入作为循环中的最后一项。示例:
public static void loopTest()
{
Scanner reader = new Scanner(System.in);
int n = 0;
int sum = 0;
System.out.println("Type a number then press enter... type '-1' to sum the numbers and exit");
n = Integer.parseInt(reader.nextLine());
while (n != -1)
{
sum = sum + n;
n = Integer.parseInt(reader.nextLine());
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum ); // <-- Does
}
publicstaticvoidlooptest()
{
扫描仪阅读器=新扫描仪(System.in);
int n=0;
整数和=0;
System.out.println(“键入一个数字,然后按enter…键入“-1”将数字相加并退出”);
n=Integer.parseInt(reader.nextLine());
而(n!=-1)
{
sum=sum+n;
n=Integer.parseInt(reader.nextLine());
}
System.out.println(“谢谢,待会儿见!”);
System.out.println(“总和是”+sum);//您也在减去最后的-1。@Marvin是对的:您的循环也使用-1进行算术运算。在打印之前(或打印++sum
),在示例中只需添加一个数字(1)给出的总和sum
=1。但是,正如其他人所说,您减去第二个输入(-1),这只会停止求和。这样做会在应该有1的情况下给您一个0的总和(如错误消息中所述)。注意,在将n
的值相加(或减去)之前,您不会检查该值。
public static void loopTest()
{
Scanner reader = new Scanner(System.in);
int n = 0;
int sum = 0;
System.out.println("Type a number then press enter... type '-1' to sum the numbers and exit");
n = Integer.parseInt(reader.nextLine());
while (n != -1)
{
sum = sum + n;
n = Integer.parseInt(reader.nextLine());
}
System.out.println("Thank you and see you later!");
System.out.println("The sum is " + sum ); // <-- Does
}