我必須編寫一個程序,要求用戶輸入整數,但必須是積極的。 我很確定我必須使用循環,並且不要以爲我被允許使用Math.abs()。在java中獲取用戶輸入的正整數
我現在寫的東西看起來很亂。下面是代碼:
public class Q1{
public static void main(String[] args){
int num1, num2, num3;
while(true){
System.out.println("Input first integer.");
num1 = TextIO.getInt();
if(num1 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input second integer.");
num2 = TextIO.getInt();
if(num2 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
while(true){
System.out.println("Input third integer.");
num3 = TextIO.getInt();
if(num3 > 0)
break;
System.out.println("Integer isn't positive. Try again");
}
....
}
}
我基本上只是做了單獨的,而對於每個整數循環來測試,如果整數爲正,因爲當我使用一個循環,我不能讓它正常運行。有沒有一種方法只使用一個循環,仍然可以工作,但看起來更整潔?
您可以將整數存儲在數組中嗎? –
用戶需要輸入任意數量的整數?或者你知道提前多少次? – Kon