我正在尝试编写一个java控制台菜单,但我无法在控制台中呈现它。这是我到目前为止编写的代码。
package com.registrar;
import java.util.*;
class GUIMenu {
private Course[] courses = new Course[100];
private Person[] persons = new Person[1000];
public void display_menu() {
System.out.println("****************MENU*****************");
System.out.println("[1] Add Course\n[2] Add Student to Course \n[3] Verify Registration \n[4] Remove Student \n[5] Add Persons");
System.out.println("**************************************");
System.out.println("Selection: ");
}
public GUIMenu(){
Person p = null;
Scanner in = new Scanner (System.in);
int input = in.nextInt();
switch (input){
case 1:
Scanner sc = new Scanner(System.in);
System.out.println("Enter Course Name: ");
String name = sc.nextLine();
System.out.println("Enter Course ID:");
Integer cID = sc.nextInt();
System.out.println("Enter Instructor ID:");
Integer pn = sc.nextInt();
for(int i = 0; i < persons.length; i ++){
System.out.println(persons[i]);
}
for(int i = 0; i<persons.length; i++){
if(persons[i] !=null){
if(persons[i].getId().intValue() == pn){
System.out.println("Record Found");
p = persons[i];
}
else
System.out.println("Record Not Found");
}
}
Course c = new Course(name, cID);
if(p!=null){
Instructor ins = new Instructor(p);
c.setInstructor(ins);
}
System.out.println(c + " has been created");
for(int i = 0; i < courses.length; i ++){
if(courses[i] == null){
courses[i] = c;
break;
}
}
new GUIMenu();
case 2:
for(int i = 0; i < courses.length; i ++){
if(courses[i] != null)
System.out.println(courses[i]);
}
break;
case 3:
System.out.println ( "You picked option 3" );
break;
case 4:
System.out.println ( "You picked option 4" );
break;
case 5:
Scanner pers = new Scanner(System.in);
System.out.println("Enter Person Name: ");
String pname = pers.nextLine();
System.out.println("Enter Person ID:");
Integer oiID = pers.nextInt();
Person per = new Person(pname, oiID);
for(int i = 0; i < persons.length; i ++){
if(persons[i] == null){
persons[i] = per;
break;
}
}
display_menu();
default:
System.err.println("Unrecognized option");
}
}
public static void main ( String[] args ) {
GUIMenu a = new GUIMenu();
a.display_menu();
}
}
我正在尝试在菜单上选择后,代码在完成与该特定选择相关联的代码后再次返回菜单。我做错了什么?我根本没看到菜单。
答案 0 :(得分:2)
我做错了什么?
查看代码:这是它开始的地方:
public static void main ( String[] args ) {
GUIMenu a = new GUIMenu(); // This is executed first...
a.display_menu();
}
让我们来看看它
public GUIMenu(){
Person p = null;
Scanner in = new Scanner (System.in);
int input = in.nextInt(); // this is where it's waiting for your input.
...
查看代码流程,很清楚为什么菜单没有显示。
修改强>
你正在寻找这样的东西:
public void runApplication() {
// init Scanner
boolean nextRound = true;
while(nextRound) {
displayMenu();
int input = sc.nextInt();
switch(input) {
case 1: // do stuff
break;
case 2: // this is the exit command
nextRound = false;
break;
// more cases
default:
// undefined input
}
}
}
因此,您只将构造函数用于构造函数相关代码,然后调用runApplication()
方法。