gpt4 book ai didi

Java 类和扫描器

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:47 25 4
gpt4 key购买 nike

我正在学习java并从类(class)开始,我现在有一些疑问。

我将使用学生、类(class)和主席的数据制作一个程序。例如,学生数据中的信息将用于教室和椅子。现在,我将仅限于类(class)学生。

每个学生都有姓名和出生日期。我想我应该创建一个包含学生数据的类,然后将学生的数据保存在两个数组中。名称的一维字符串数组和日期(年、月、日)的三列数组。

我首先使用代码创建 Student 类:

    public class Stundent{
private String nameStudent;
private int yearBirth;
private int monthBirth;
private int dayBirth;

public void setName(String name){
System.out.println("Insert student's name:");
nameStudent = name;

}
public String getName(){
return nameStudent;
}
public void setYear(int year){
System.out.println("Insert student's year of birth:");
yearBirth = year;
}
public int getYear(){
return yearBirth;
}
public void setMonth(int month){
System.out.println("Insert student's month of birth:");
monthBirth = month;
}
public int getMonth(){
return monthBirth;
}
public void setDay(int day){
System.out.println("Insert student's day of birth:");
dayBirth = day;
}
public int getDay(){
return dayBirth;
}
}

然后在主文件中是这样想的:

            Student person = new Student();
String[] nameStudents = new String[100];
int[][] birthdayStudents = new int[100][3];
for (int i = 0; i < 3; i++){

person.setName(sc.nextLine());
nameStudents[i] = person.getName();

person.setAno(sc.nextInt());
birthdayStudents[i][1] = person.getAno();

person.setMes(sc.nextInt());
birthdayStudents[i][1] = person.getMes();

person.setDia(sc.nextInt());
birthdayStudents[i][2] = person.getDia();

}

第一个问题:

忘记了这是因为扫描仪无法正常工作,这是正确的思维方式吗?

第二个问题:

如果我运行这段代码,我会遇到以下情况:它将向我显示“插入学生姓名:”,但如果我放置,则会出现 Maria InputMismatchException。我相信他当年就储存了玛丽亚。为什么会出现这种情况?在同一个 for 循环中,我不能对扫描仪进行多次调用吗?如果我只输入代码:

person.setName(sc.nextLine());
nameStudents[i] = person.getName();

并删除所有与生日有关的内容,它就可以正常工作了。谁能帮我解答一下吗?

最佳答案

我认为这不是正确的做法。您将实体学生与输入相关信息混合在一起。我将其重新设计如下(稍微减少学生):

/* just an entity, no logic at all */
public class Student {
private String name = null;
private Integer year = null;

public void setName(String name){
this.name = name;
}

public void setYear(Integer year){
this.year = year;
}
}

以及获取用户输入的逻辑:

List<Student> students = new ArrayList<Student>();
int numberOfStudents = 3;

for (int i = 0; i < numberOfStudents; i++){
System.out.println("Please enter name:");
String name = sc.nextLine();

System.out.println("Please enter year:");
Integer year = sc.nextInt();

/* after gathering the input create student */
Student s = new Student();
s.setName(name);
s.setYear(year);

students.add(s);
}

关于Java 类和扫描器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7955381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com