[英]How to check if integer is positive or negative in a WHILE loop in Java?
我需要編寫一個名為 SumAndAverage 的程序來產生 1、2、3、...、N 的總和,其中 N 是用戶輸入的正 integer 數。 該程序應
使用 While 循環;
檢查用戶輸入,如果N不是正的integer數,則要求用戶重新輸入有效值;
計算機並顯示 1,2,3,...,to N 的平均值;
用一位十進制數顯示 output。
我已經正確創建了循環,但是,我無法弄清楚如何檢查 integer 是正還是負。 我是 Java 的新手,因此我們將不勝感激!
到目前為止,這是我的代碼:
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();
}
}
要檢查 var N 是負數還是正數,只需使用以下代碼:
if(n < 0){
System.out.println("Wrong value, please write a positive integer");
} else{
PROGRAM
}
我希望這對你有幫助
do-while 循環可以完成這項工作。
int N;
do {
N = keyboard.nextInt();
}
while (N < 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.