3 回答
TA贡献1779条经验 获得超6个赞
这里没有很多信息,但我看到一个问题肯定会导致您的问题。
当您从一行中读取一个数值,并期望用户点击返回来提交该值时,您必须先消耗行尾才能继续。扫描仪不会自动执行此操作。要让用户输入 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);
}
TA贡献1804条经验 获得超2个赞
当您读取 4 个值时,您需要sc.nextLine()在从输入中读取第一个 int 后调用。 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;
}
}
}
TA贡献1866条经验 获得超5个赞
以前的解决方案并不完全正确。经过一点调试会话后,我想出了以下解决方案:
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。
添加回答
举报