[英]Why does my code not run?
I have this code: 我有以下代码:
import java.util.Scanner;
public class PositiveNegative { public static void main(String[] args) {
int numbers, plus = 0, minus = 0;
int count = 0;
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while(numbers != 0)
{
total += numbers;
if(numbers > 0)
plus++;
if(numbers < 0)
minus++;
}
System.out.println("The number of positives is: " +plus);
System.out.println("The number of negatives is: " +minus);
System.out.println("The number of total is: " +total);
}
}
The problem with is that I try to run it and type the numbers but it does nothing. 问题是我尝试运行它并键入数字,但是它什么也没做。 I want it so that when you type 0 it stops taking numbers and starts processing the code. 我想要它,以便当您键入0时,它停止输入数字并开始处理代码。 What should I do? 我该怎么办?
You need to update numbers
or your loop will run for ever. 您需要更新numbers
否则循环将永远运行。 And I recommend using braces (and an else
). 我建议使用括号(和else
)。 Something like, 就像是,
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
while (numbers != 0) {
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
}
Alternatively, you could use a do-while
loop. 另外,您可以使用do-while
循环。 Then you only need one copy of the prompt. 然后,您只需要一份提示。 Like, 喜欢,
do {
System.out.print("Enter an integer (0 to quit): ");
numbers = scan.nextInt();
total += numbers;
if (numbers > 0) {
plus++;
} else if (numbers < 0) {
minus++;
}
} while (numbers != 0);
Try this: 尝试这个:
import java.util.Scanner;
public class PositiveNegative {
public static void main(String[] args) {
int numbers = 0, plus = 0, minus = 0;
double total = 0;
do{
Scanner scan = new Scanner(System.in);
System.out.print("Enter an integer (0 to quit): ");
numbers = Integer.valueOf(scan.nextLine());
total += numbers;
if (numbers > 0)
plus++;
if (numbers < 0)
minus++;
}
while (numbers != 0);
System.out.println("The number of positives is: " + plus);
System.out.println("The number of negatives is: " + minus);
System.out.println("The number of total is: " + total);
}
}
Put your Scanner in the while loop so that everytime loop start it will ask for User input. 将Scanner放入while循环中,以便每次循环启动时都将要求用户输入。
You have to modify numbers
each time to make it work in your while
. 你要修改numbers
每次都让它在你的工作while
。
So, in your existing code, just comment out numbers = scan.nextInt();
因此,在您现有的代码中,只需注释掉numbers = scan.nextInt();
and use below-- 并在下面使用-
// numbers = scan.nextInt(); //comment out this call
while ((numbers = scan.nextInt()) != 0) {
....
this will give you desired output-- 这将为您提供所需的输出-
Enter an integer (0 to quit): 9
4
-9
1
0
The number of positives is: 3
The number of negatives is: 1
The number of total is: 5.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.