我对 Java 和一般编码有点陌生,我遇到了一个到目前为止我无法解决的问题。功能是: 一个开关菜单,要求将输入保存在数组中(选项 1),然后使用第二个选项打印数组中对象的属性。
我有一个自定义类:
课程
public class Course {
String name_course;
String code_course;
int credits_course;
Course(String name, String code, int credits){
this.name_course = name;
this.code_course = code;
this.credits_course = credits;
}
}
在另一个文件中,我定义了一个函数,用于将用户的输入保存在数组中,还定义了循环遍历数组并打印值的函数。
public class Logic{
static BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
static PrintStream out = System.out;
//I believe this function does not save correctly the input on the array
static Course[] course = new Course[6];
public static void register_course(String name, String code, int credits) {
for (int i = 0; i < course.length; i++) {
course[i] = new Course(name, code, credits);
}
// This only prints one value as the previous function is likely wrong
public static void print_course(Course[] pcourse) {
for (int i = 0; i < course.length; i++) {
out.println(course[i]);
}
}
}
这是我在主上的开关
// Just to clarify I have a do while loop that loops over the switch but I won't include it, it works fine
public static void process_option(int pOption) throws IOException{
switch(pOption){
case 1:
out.println("Name");
String name = in.readLine();
out.println("Code");
String code = in.readLine();
out.println("Credits");
int credits = Integer.parseInt(in.readLine());
Logic.register_course(name, code, credits);
break;
case 2:
Logic.print_course(Logic.course);
break;
}
我非常感谢任何帮助找出我的错误。谢谢。