繁体   English   中英

使用扫描仪创建ArrayList

[英]Creating an ArrayList using a Scanner

我正在做一个使用数组列表创建学生列表的项目。 我知道如何创建一个简单的数组列表,但是,我决定要使用Scanner方法。 不幸的是,那是我的麻烦开始的地方。 这是我的起源类的样子:

import java.util.Scanner;

/**
 * Used to create a single student.
 */

public class Student
{
private String Name;
private int Age;
private String Gender;
private int heightInches; //inches%maxInches
private int heightFeet; //inches/maxInches
private int Inches;
private final int maxInches = 12;
private int Weight;
private String Position;
private Scanner keybd;

/**
 * Constructor
 */
public Student(){
    keybd = new Scanner(System.in);
    setStudent();
}

/**
 * Method to create a student
 */
public void setStudent(){
    System.out.println("Enter name of student:");
    Name = keybd.next();
    System.out.println("Enter age of student:");
    Age = keybd.nextInt();
    System.out.println("Enter gender of student:");
    Gender = keybd.next();
    System.out.println("Enter height in inches of student:");
    Inches = keybd.nextInt();
    if(Inches>= maxInches){
        heightFeet = Inches/maxInches;
        heightInches = Inches%maxInches;
    }
    else{
        heightInches = Inches%maxInches;}
    System.out.println("Enter position of user:");
    Position = keybd.next();
    System.out.println("Enter weight of student:");
    Weight = keybd.nextInt();
}

/**
 * Returns height of student
 */
public void getHeight(){
    System.out.println(heightFeet + "'" + heightInches + "''");
}

/**
 * Prints details of student
 */
public void printDetails(){
    if((Position.equals("Doctor")) || (Position.equals("Coach"))){
        System.out.println(Name + " who is a " + Age + " year old " + Gender + " weighs " + Weight + " and is ");
        getHeight();}
    else{System.out.println(Name + " who is a " + Age + " year old " + Gender + " is ");
        getHeight();
    }
}

}

不幸的是,当我尝试在新的类中调用setStudent方法时,该方法将调用Student类以便实际创建列表,但遇到了问题。 我真的很想在扫描程序中添加一个“ if”语句,如果用户希望添加另一个学生,它将循环播放,否则将结束,但是,由于我什至无法使用上述代码创建一个新的学生,所以它不是甚至值得我花时间尝试一下。

每个Student对象都是其自己的Student类实例。 当您在构造函数中读取所有数据时,便可以使用该特定的Student对象。 您可以在构造函数中创建一个循环,以创建新的Student对象,但这将相当令人困惑-毕竟,构造函数的工作是创建一个对象。

(此外,让构造函数要求用户输入是不好的样式。它使该类在单元测试中不可测试,并将其与控制台绑定,使其在GUI程序中不可用。您最好阅读以下内容所有其他学生数据,然后将其传递给Student构造函数。)

因此,Student类之外的一些代码(例如,您的main方法)应具有Student列表,收集输入并创建Student对象。

我决定尝试使它保持简单(很长一段时间以来第一次,我采用了简单的方法)在我的新课上写了:

/**
 * Method to add more students
 */
public void addStudent(){
    studentList.add  (new Student());
}

从好的方面来说,现在我可以尝试使用if-else方法添加更多学生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM