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。
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);
}
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;
}
}
}
为您提供一些解释:方法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()
扫描下一个标记作为输入值。但最重要的是Return不算在内,因为您的bash将此视为您的输入。
此外,您的键盘输入是本地解释的,特别是如果您想读取双精度字。例如,英语分隔符写为DOT,德语写为
COMMA。