繁体   English   中英

扫描器未将值分配给arrayList

[英]Scanner does not assign value to the 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测试的值分配给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)

“ 0”是arrayList的大小,所以我认为在加值过程中可能会出现一些问题

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

而且我也尝试过解决与我类似的其他人的问题的解决方案,但这是行不通的。 您能帮我解决这些问题吗?

一些建议,可能会帮助您更好地解决问题:

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

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

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

您发布的异常将永远无法实现,因为您总是会陷入绑定异常之外的索引中。 同样,您从索引= 1开始,可能要从索引0开始。不确定您在Score类中的逻辑。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM