作者:感觉ly_382 | 来源:互联网 | 2023-09-25 14:33
我有一个任务:
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 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 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 if (grades[k]>highest) {
highest = grades[k];
order = k;
}
}
return names[order];
}
}
之所以会发生这种情况,是因为令牌的默认定界符是空格。您只需在启动Scanner对象时设置一些配置即可:
Scanner input = new Scanner(System.in).useDelimiter("\\n");