java - 尝试输入带有空格的字符串时出现 InputMismatchException

标签 java arrays loops inputmismatchexception

我有一个任务:

5-8)(求最高分)编写一个程序,提示用户输入学生人数以及每个学生的姓名和分数,最后显示分数最高的学生的名字。

当我运行此代码并输入“john”等名称时,它运行良好,但当我尝试输入“John Doe”等名称时,它会抛出 InputMismatchException。 我尝试使用 nextLine() 但程序会移动到下一个项目,而无需等待用户输入数据。最后,仍然抛出InputMismatchException错误。截图:ibb.co/ZT2ZhMz

解决方案:我创建了一个新的 Scanner 对象 Scanner inp = new Scanner(System.in).useDelimiter(""); 并用它输入了名称。

package pp;

import java.util.Scanner;

public class BestStudent {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the number of students: ");
        int nos = input.nextInt();

        //Creating arrays to store the inputs
        String []names = new String[nos];
        double []grades = new double[nos];

        //A loop for getting inputs until it reaches number of students(nos) value
        for (int i = 0; i<nos; i++) {
            System.out.println("Student "+(i+1)+" of "+nos);
            System.out.println("Enter student's name: ");
            names[i] = input.next();

            System.out.println("Enter student's score: ");
            grades[i] = input.nextDouble();
        }
        System.out.println("The highest score was:"+highest(grades)+" and "+name(names, grades)+" got it.");


        input.close();
    }
    //A method for finding the highest value
    public static double highest (double []grades) {
        double highest = 0;
        for (int k = 0; k<grades.length; k++) {

            if (grades[k]>highest)
                highest = grades[k];
        }
        return highest;
    }

    //A method for the order of the name that has the highest value.
    public static String name(String []names, double []grades) {
        double highest = 0;
        int order = 0;
        for (int k = 0; k<grades.length; k++) {

            if (grades[k]>highest) {
                highest = grades[k];
                order = k;
            }

        }
        return names[order];

    }

}

enter image description here

最佳答案

发生这种情况是因为标记的默认分隔符是空格。您只需在初始化 Scanner 对象时设置一些配置:

Scanner input = new Scanner(System.in).useDelimiter("\\n");

关于java - 尝试输入带有空格的字符串时出现 InputMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59444140/

相关文章:

java - Play : Custom Ebean constraints

php - mysql php数组转特定格式

javascript - ReactJs + Redux ---> 尝试调用企业名称,其中 item.business_id === BusinessId

javascript - 填充数组失败

c - 在 C 中使用数组(输出错误)

java - 如何强制Java进程在热点崩溃时退出

java - 如何使用脚本通过Java API更新elasticsearch文档中的一个字段?

java - 无法在Spring Cloud Stream kafka中设置kafka属性

java - While-Loop 完成问题和最终值计算

python - 乘以来自Python中两个单独列表的 float