简体   繁体   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());

    }

}

The above is my code and I have a problem of assigning value from Scanner test to ArrayList score. 上面是我的代码,我在将Scanner测试的值分配给ArrayList分数时遇到问题。 When I run the code, this shows that 当我运行代码时,这表明

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" is the size of the arrayList, so I think that there may be some problem during the value adding “ 0”是arrayList的大小,所以我认为在加值过程中可能会出现一些问题

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

and also I have tried the solutions for others' questions similar to mine,but it does not work. 而且我也尝试过解决与我类似的其他人的问题的解决方案,但这是行不通的。 Could you please help me with these question? 您能帮我解决这些问题吗?

Some suggestions and that might help you get it off better : 一些建议,可能会帮助您更好地解决问题:

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

This loop will terminate only if you enter some non-digit character. 仅当您输入一些非数字字符时,此循环才会终止。 Space and new line will not terminate the loop. 空格和换行符不会终止循环。

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

Exception you posted, will never be reached because you will always end up into index out of bound exception. 您发布的异常将永远无法实现,因为您总是会陷入绑定异常之外的索引中。 Also, you are starting with index = 1, you might want to start from index 0. Not sure about your logic in Score class. 同样,您从索引= 1开始,可能要从索引0开始。不确定您在Score类中的逻辑。

Also, as what others said, if you posted exception from any class, please provide that. 另外,正如其他人所说,如果您发布了任何课程的例外情况,请提供该例外情况。

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

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