基于JAVA控制台的基本菜单问题
我正在尝试创建一个基于java控制台的基本菜单系统。我已设法使第一层工作正常:基于JAVA控制台的基本菜单问题,java,Java,我正在尝试创建一个基于java控制台的基本菜单系统。我已设法使第一层工作正常: public static int menu(){ //Displays the main menu and handles passing off to next menu. Scanner scanner = new Scanner (System.in); int selection=0; String CDid; int i=0; in
public static int menu(){
//Displays the main menu and handles passing off to next menu.
Scanner scanner = new Scanner (System.in);
int selection=0;
String CDid;
int i=0;
int j=0;
while(i==0) { //changed while(1) to a value that didn't complain in netbeans
System.out.println("Please choose an option from the following:");
System.out.println("[1] Search by CD ID");
System.out.println("[2] View all CD's in store");
System.out.println("[3] Quit");
System.out.println("Choice: ");
selection=scanner.nextInt();
switch (selection){
case 1:System.out.println("Please enter the CD ID:");
i=1;
break;
case 2:System.out.println("List all CD's");
i=1;
break;
case 3:System.out.println("Quiting...");
System.exit(5);
default:System.out.println("Your choice was not valid!");
};
}
return selection;
}
我现在正试图这样做,当您选择选项[1]时,它将接受您输入的下一个字符串并运行showCD()方法。我曾经尝试过我以前使用的方法,但由于它是一个字符串,我遇到了一些错误
public static int menu(){
//Displays the main menu and handles passing off to next menu.
Scanner scanner = new Scanner (System.in);
int selection=0;
String CDid;
int i=0;
int j=0;
while(i==0) { //changed while(1) to a value that didn't complain in netbeans
System.out.println("Please choose an option from the following:");
System.out.println("[1] Search by CD ID");
System.out.println("[2] View all CD's in store");
System.out.println("[3] Quit");
System.out.println("Choice: ");
selection=scanner.nextInt();
switch (selection){
case 1:System.out.println("Please enter the CD ID:");
CDid=scanner.toString();
while(j==0) {
switch (CDid){
case 1:showCD(CDid);
j=1;
break;
default:System.out.println("Your choice was not valid!");
}
}
i=1;
break;
case 2:System.out.println("List all CD's");
i=1;
break;
case 3:System.out.println("Quiting...");
System.exit(5);
default:System.out.println("Your choice was not valid!");
};
}
return selection;
}
听起来像是家庭作业(你应该给它贴上这样的标签)。您正试图获取下一个用户输入字符串,但您的代码正在调用scanner.toString()
。这只会打印出扫描仪对象的字符串表示形式。您可能想改用scanner.nextLine()
。请看一看以供参考
编辑:另外,只要进一步阅读代码,您就会尝试打开CDid,它是一个字符串。您不能在Java中打开字符串(但是如果您change:CDid=scanner.toString() to:CDid=scanner.next()
我不确定是否可以使用字符串进行切换…如果无法使用Integer.parseInt()方法将CDid解析为Integer,则扫描仪上没有nextString方法。(无论如何,这是在1.6中)。