public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int iteam = sc.nextInt();
Student[] students = new Student[iteam];
int id;
String name;
String city, s_city;
double marks, s_marks;
for (int i = 0; i < iteam; i++) {
id = sc.nextInt();
name = sc.nextLine();
city = sc.nextLine();
marks = sc.nextDouble();
students[i] = new Student(id, name, city, marks);
}
}
我收到一个错误“ Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)"
我也尝试使用next(),但存在相同的错误。并且我还导入了java.util.Scanner。
答案 0 :(得分:0)
这里没有很多信息,但是我看到一个肯定会引起您问题的问题。
当您从一行中读取一个数字值,并期望用户按下回车键以提交该值时,您必须先消耗行尾,然后才能继续。扫描仪不会自动执行此操作。要让用户输入4个值,每次输入后都按回车键,您的输入循环应如下所示:
for (int i = 0; i < iteam; i++) {
id = sc.nextInt(); sc.nextLine();
name = sc.nextLine();
city = sc.nextLine();
marks = sc.nextDouble(); sc.nextLine();
students[i] = new Student(id, name, city, marks);
}
答案 1 :(得分:0)
以前的解决方案不正确。经过一些调试会话后,我想出了以下解决方案:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int iteam;
iteam = sc.nextInt();
Student[] students = new Student[iteam];
int id;
String name;
String city;
double marks;
for (int i = 0; i < iteam; i++) {
id = sc.nextInt();
name = sc.next();
city = sc.next();
marks = sc.nextDouble();
students[i] = new Student(id, name, city, marks);
}
}
为您提供一些解释:方法next()
,nextInt()
和nextDouble()
扫描下一个标记作为输入值。但最重要的是Return不算在内,因为您的bash将此视为您的输入。
此外,您的键盘输入是本地解释的,特别是如果您想读取双精度字。例如,英文分隔符写为 DOT ,德语写为 COMMA 。
答案 2 :(得分:0)
在读取4个值时,需要从输入中读取第一个int后调用sc.nextLine()
。
Scanner#nextInt()
仅读取整数,但不读取换行符"\n"
;您将需要使用Scanner#nextLine
使用换行符。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int iteam = sc.nextInt();
Student[] students = new Student[iteam];
int id;
String name;
String city, s_city;
double marks, s_marks;
for (int i = 0; i < iteam; i++) {
id = sc.nextInt();
sc.nextLine();//call next line to prevent exception
name = sc.nextLine();
city = sc.nextLine();
marks = sc.nextDouble();
students[i] = new Student(id, name, city, marks);
}
}
完整的示例:
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int iteam = sc.nextInt();
Student[] students = new Student[iteam];
int id;
String name;
String city, s_city;
double marks, s_marks;
for (int i = 0; i < iteam; i++) {
id = sc.nextInt();
sc.nextLine();
name = sc.nextLine();
city = sc.nextLine();
marks = sc.nextDouble();
students[i] = new Student(id, name, city, marks);
}
for(Student s: students){
System.out.println(s);
}
}
private static class Student{
private int id;
private String name;
private String city;
private double marks;
public Student(int id, String name, String city, double marks){
this.id = id;
this.name = name;
this.city = city;
this.marks = marks;
}
public String toString(){
return "[Student] Id: "+this.id+", Name: "+this.name+", City: "+this.city+", Mark: "+this.marks;
}
}
}