我的目標是詢問用戶一系列數字,一旦他達到最多20個數字或輸入負數時,它只會停止詢問更多數字。但是我只想使用這個系列,當這個數字的總和小於50並且沒有數字超過15時。重複詢問一系列數字,直到系列有效
這是我迄今爲止寫的,我不明白爲什麼它不起作用
import java.util.Scanner;
class numbersSeries {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] numbers = new int[20];
boolean invalid = true;
int sum = 0, input = 0, counter = 0;
while (invalid == true) {
System.out.print("Series ");
while ((input = in.nextInt()) > 0 && counter < 19) {
numbers[counter] = input;
sum += numbers[counter];
boolean hasbignumber = false;
if(numbers[counter] > 15) {
hasbignumber = true;
}
if(sum < 50 && hasbignumber == false) {
invalid = false;
}
counter++;
}
}
}
}
編輯! 我忘了提一件很重要。一旦該系列被丟棄的循環會從頭再來,利用這個輸出例如
Series 1 2 4 30 -3 //this series will be discarded because the fourth value surpasses the maximum of 20
Series 4 9 8 8 3 8 6 1 15 15 -2 //this one too because the sum is over 50
Series 3 1 9 0 -2 //only this one is going to be used because it fits all conditions
因此,所有我想要的是讓編譯器繼續要求新的系列,直到一個有效的介紹,所以我可以用它後方。
歡迎來到Stackoverflow。現在你在這裏,你應該學會如何以聰明的方式提出問題,以獲得有用答案的絕佳機會。首先,你的程序不工作的是什麼?理想和觀察行爲之間的具體區別是什麼? 「尋求調試幫助的問題(」爲什麼這個代碼不工作?「)必須包含所需的行爲,特定的問題或錯誤以及在問題本身中重現問題所需的最短代碼。沒有明確問題陳述的問題對其他讀者沒有用處。「 –
要輸入20個數字,我認爲您需要'counter <20'或'counter <= 19'。 –