[英]How to check if integer is positive or negative in a WHILE loop in Java?
I need to write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to N, where N is a positive integer number inputted by the user.我需要编写一个名为 SumAndAverage 的程序来产生 1、2、3、...、N 的总和,其中 N 是用户输入的正 integer 数。 The program should该程序应
Use the While loop;使用 While 循环;
Check the user's input, and ask the user re-input a valid value if N is not a positive integer number;检查用户输入,如果N不是正的integer数,则要求用户重新输入有效值;
Computer and display the average of 1,2,3,...,to N;计算机并显示 1,2,3,...,to N 的平均值;
Display the output with one decimal number.用一位十进制数显示 output。
I have created the loop correctly, however, I am unable to figure out how to check if the integer is positive or negative.我已经正确创建了循环,但是,我无法弄清楚如何检查 integer 是正还是负。 I am new to Java so any help would be greatly appreciated!我是 Java 的新手,因此我们将不胜感激!
Here is my code so far:到目前为止,这是我的代码:
import java.util.Scanner;
public class SumAndAverage {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("*********");
System.out.println();
System.out.print("Please input a positive integer number: ");
int N = keyboard.nextInt();
int i = 1 ;
int sum = 0;
while(i <= N)
{
sum += i;
i++;
}
System.out.println();
System.out.println("The sum from 1 to " + N + " is: " + sum);
System.out.println();
System.out.printf("The average is: %d%n", sum/N);
System.out.println();
System.out.println("*********");
keyboard.close();
}
}
To check if the var N is negative or positive just use the code below:要检查 var N 是负数还是正数,只需使用以下代码:
if(n < 0){
System.out.println("Wrong value, please write a positive integer");
} else{
PROGRAM
}
I hope this help you我希望这对你有帮助
A do-while loop can do this job. do-while 循环可以完成这项工作。
int N;
do {
N = keyboard.nextInt();
}
while (N < 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.