我正在編寫一個應該讀取0-100分數(最多100分)的未指定數量的作業的程序,並且在-1或任何後面停止輸入負數。 我已經把它放到Do while循環中,當通過掃描器拉入-1時,它被設置爲終止。該循環有一個計數器,用於記錄循環已經經過了多少次,一個加法器將所有輸入行加在一起以便稍後計算平均值,以及一種方法在輸入值已經檢查後發送給數組看看這個數字是否爲-1。 而不是這樣做,循環只增加計數器每2個循環,-1將只在一個偶數循環數終止循環,否則它會等到下一個循環終止。這完全讓我感到困惑,我不知道它爲什麼這樣做。有人能指出這個錯誤嗎?提前致謝!這是我迄今爲止所有的。Java while循環跳過行,每2個循環做一次
import java.util.Scanner;
public class main {
//Assignment 2, Problem 2
//Reads in an unspecified number of scores, stopping at -1. Calculates the average and
//prints out number of scores below the average.
public static void main(String[] args) {
//Declaration
int Counter = 0; //Counts how many scores are
int Total = 0; //Adds all the input together
int[] Scores = new int[100]; //Scores go here after being checked
int CurrentInput = 0; //Scanner goes here, checked for negative, then added to Scores
Scanner In = new Scanner(System.in);
do {
System.out.println("Please input test scores: ");
System.out.println("Counter = " + Counter);
CurrentInput = In.nextInt();
Scores[Counter] = CurrentInput;
Total += In.nextInt();
Counter++;
} while (CurrentInput > 0);
for(int i = 0; i < Counter; i++) {
System.out.println(Scores[i]);
}
System.out.println("Total = " + Total);
In.close();
}
}
如果您遵循Java命名約定,那麼您的代碼將更具可讀性。例如。變量以小寫字母開頭。 – jlordo 2013-02-12 00:33:41