2013-02-12 319 views
1

我正在编写一个应该读取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(); 


} 

} 
+7

如果您遵循Java命名约定,那么您的代码将更具可读性。例如。变量以小写字母开头。 – jlordo 2013-02-12 00:33:41

回答

6
CurrentInput = In.nextInt(); 
    Scores[Counter] = CurrentInput; 
    Total += In.nextInt(); 

要调用两次In.nextInt(),即你正在阅读在每次循环迭代两行。

1
CurrentInput = In.nextInt(); 
Scores[Counter] = CurrentInput; 
Total += CurrentInput; 

改为使用它。