我试图将输入数量限制为大于0和整数。
代码在这里:
import java.util.Scanner;
public class PROB4_CHAL1 // Sum of Numbers
{
public static void main(String[] args)
{
int sum = 0;
int count = 1;
int number = 1;
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer " +
"greater than 0.");
number = input.nextInt();
while (number >= count)
{
sum += count;
count ++;
}
System.out.println("Sum equals " + sum);
}
}
Java新手,所以一切都会有所帮助!
答案 0 :(得分:2)
您可以在while循环中获取输入,如下所示:
int number = 0; // start at 0 so the while loop is true for the first time
while (number < 1) {
System.out.println("Enter an integer " +
"greater than 0.");
number = input.nextInt();
}
这样它会一直要求他们输入一个数字,直到他们输入的数字大于0。