扫描程序不会为arrayList指定值

时间:2017-10-22 08:58:32

标签: java arraylist

import java.util.*;

public class TestScoreTestor {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ArrayList<Integer> score = new ArrayList<Integer>();
//        Scanner keyboard = new Scanner(System.in);
        Scanner test = new Scanner(System.in);      
        System.out.println("Enter the scores(enter the input by Ctrl+z): ");

//   int a = keyboard.nextInt();  // **** add this to swallow EOL token

        while(test.hasNextInt()) {
             score.add(test.nextInt());
        }   

        test.close();
        System.out.println();
        System.out.println(score.size());
// the scores are not involved  
        for (int i = 1; i <= score.size(); i++) {
            System.out.println(score.get(i));
        }

        Scores grade = new Scores(score);
        System.out.println("Your grade: " + grade.getLetterGrade());

    }

}

以上是我的代码,我有一个问题,即从Scanner test到ArrayList得分分配值。当我运行代码时,这表明

Enter the scores(enter the input by Ctrl+z): 
90 90 90
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Lab05Q6.Scores.averageScore(Scores.java:29)
    at Lab05Q6.Scores.getLetterGrade(Scores.java:36)
    at Lab05Q6.TestScoreTestor.main(TestScoreTestor.java:29)

&#34; 0&#34;是arrayList的大小,所以我认为在添加值

期间可能存在一些问题
while(test.hasNextInt()) {
             score.add(test.nextInt());
        }

我也尝试过其他人的解决方案&#39;类似于我的问题,但它不起作用。你能帮我解决一下这个问题吗?

1 个答案:

答案 0 :(得分:0)

一些建议可能有助于您更好地实现目标:

   while(test.hasNextInt()) {
             score.add(test.nextInt());
        }

只有输入一些非数字字符时,此循环才会终止。空格和换行不会终止循环。

 for (int i = 1; i <= score.size(); i++) {
            System.out.println(score.get(i));
        }

您发布的异常将永远无法访问,因为您将始终最终进入索引超出范围的异常。此外,您从index = 1开始,您可能希望从索引0开始。不确定您在Score类中的逻辑。

另外,正如其他人所说,如果您发布任何课程的例外情况,请提供。