首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在尝试输入带有空格的字符串时获取InputMismatchException

在尝试输入带有空格的字符串时获取InputMismatchException
EN

Stack Overflow用户
提问于 2019-12-22 12:20:18
回答 1查看 434关注 0票数 0

我的任务是:

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

当我使用"john“这样的名字运行这段代码时,它工作得很好,但是当我试图输入像"John”这样的名称时,它会抛出一个InputMismatchException。我尝试使用nextLine(),但程序移动到下一个项目,而不等待用户输入数据。最后,仍然抛出InputMismatchException错误。截图: ibb.co/ZT2ZhMz

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

代码语言:javascript
复制
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];

    }

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-22 13:54:07

这是因为令牌的默认分隔符是空白。当init Scanner对象时,您只需设置一些配置:

代码语言:javascript
复制
Scanner input = new Scanner(System.in).useDelimiter("\\n");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59444140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档