早上好!我试图理解Java中的类。我的任务是创建一个Employee类,一个Name类和一个Address类,并使用它们将信息存储到一个Array中。显然我的代码仍然是一个正在进行的工作,但我不明白如何使用Name类和Address类将值放入Array中。
特别是在我的开关(案例1)中,我想将每个属性的输入分配到数组中,但我不明白类实例是如何工作的。我曾尝试在线和在我的教科书中阅读,但没有一个解释是真的点击我。
这是我第一次接触Java类,所以任何有助于我将来应用这些概念的解释(而不仅仅是这个代码)都会非常感激。我真的想学习这一点,而不仅仅是完成一项硬件任务。提前感谢您的时间和思想!
import java.util.Scanner;
class Employee {
String fName = " ";
String lName = " ";
String city = " ";
String state = " ";
public static void main( String [] args ) {
int choice; //For Menu option
Scanner input = new Scanner( System.in );
boolean looping = true; //Loop the menu
while(looping == true) {
System.out.println( "1. Add New Employee" );
System.out.println( "0. Exit" );
System.out.print( "Choice: " );
choice = input.nextInt();
switch(choice) {
case 0: {
System.out.println( "Goodbye." );
looping = false;
break;
}
case 1: {
Employee [] employeeInfo = new Employee[9];
for(int i = 0; i < employeeInfo.length ; i++) {
Scanner info = new Scanner( System.in );
System.out.print( "Enter the Employee's First Name: ");
employeeInfo[i].fName = info.nextLine();
System.out.print( "Enter the Employee's Last Name: ");
employeeInfo[i].lName = info.nextLine();
System.out.print( "Enter the Employee's City: ");
employeeInfo[i].city = info.nextLine();
System.out.print( "Enter the Employee's State: ");
employeeInfo[i].state = info.nextLine();
break;
}
default:
System.out.println( "Invalid option." );
}
}
}
class Name {
private String fName;
private String lName;
//Constructors
Name() { //no parameters
fName = " ";
lName = " ";
}
Name(String fName, String lName) { //parameters
this.fName = fName;
this.lName = lName;
}
@Override
public String toString () {
return "The employee's name is: " + fName + " " + lName;
}
}
class Address {
private String city;
private String state;
//Constructors
Address() {
this.city = " ";
this.state = " ";
}
Address( String city, String state ) {
this.city = city;
this.state = state;
}
@Override
public String toString (){
return "The employee's residence is " + city + ", " + state;
}
}
}
答案 0 :(得分:0)
您的Employee[] employeeInfo = new Employee[9];
创建一个可以容纳9个Employee
个对象的数组,但每个元素最初都为null。您需要使用新的Employee
对象填充每个对象。在for
循环内,请在顶部执行此操作:
employeeInfo[i] = new Employee();
您还需要将break
移出for
循环,移至case
的底部。否则,您的程序将只输入一个人的数据,而不是九个人的数据。