如何切换结果的顺序?我希望被要求在菜单后输入输出。
Welcome to the Library! Please make a selection from the menu:
1. View.
2. Show.
Enter a choice: 1
然而,我首先输入输入,我看到: 输入选项:1 欢迎来到图书馆!请从菜单中选择: 1.查看。 2.显示。
这是我的代码:
import java.util.*;
public class Store {
public static void main(String[] args) {
new Store().use();
}
public void use() {
char choice;
while ((choice = readChoice()) != 'X') {
switch (choice) {
case 1: view(); break;
case 2: show(); break;
default: help(); break;
}
}
}
private char readChoice() {
return In.nextChar();
}
private String view() {
return "";
}
private String show() {
return "";
}
}
private void help() {
System.out.println("Welcome! Please make a selection from the menu:");
System.out.println("1. View.");
System.out.println("2. Show."); }
答案 0 :(得分:1)
只需在help()
方法上添加use()
:
public void use() {
help();
char choice;
while ((choice = readChoice()) != 'X') {
switch (choice) {
case 1: view(); break;
case 2: show(); break;
default: help(); break;
}
}
}
您还需要分别将1
和2
更改为'1'
和'2'
,因为您正在切换char
。此编译的事实是因为编译器应用 narrowing primitive conversion 将int
转换为char
。
答案 1 :(得分:0)
我认为有三个原因导致代码没有达到预期效果。
首先输入输入,因为在控制台上打印任何内容之前,会调用readChoice()函数。等待直到从控制台读取一个字符然后返回。因此,您必须在while循环之前调用一次Help()函数。
我猜开关盒不符合您的预期。我的意思是当你输入1或2时,不会调用view()和show()函数。原因是你读取1和2作为字符而不是整数。所以switch-case应改为:
switch (choice) {
case '1': view(); break; //1 changed to '1'
case '2': show(); break; //2 changed to '2'
default: help(); break;
}
我想你可能忘记在阅读角色之前打印“输入选择:”。 (我使用了System.out.print()而不是System.out.println(),因为看起来“输入一个选项:”并且输入的选项应该在同一行中。
private char readChoice() {
System.out.print("Enter a choice:");
return In.nextChar();
}
这是整个代码,希望它能正常工作(我发表评论让你看到我做了哪些改变):
import java.util.*;
public class Store {
public static void main(String[] args) {
new Store().use();
}
public void use() {
char choice;
help();//called help() once before the loop
while ((choice = readChoice()) != 'X') {
switch (choice) { //cases changed
case '1': view(); break;
case '2': show(); break;
default: help(); break;
}
}
}
private char readChoice() {
//printing "Enter a choice:"
System.out.print("Enter a choice: ");
//I used Scanner class to read the next char, because I don't have 'In' class to use.
//you might write "return In.nextChar();" insead of the following lines
Scanner reader = new Scanner(System.in);
char c = reader.next().charAt(0);
return c;
}
private String view() {
System.out.println("you selected view"); //to see this function is called
return "";
}
private String show() {
System.out.println("you selected show"); //to see this function is called
return "";
}
private void help() {
System.out.println("Welcome! Please make a selection from the menu:");
System.out.println("1. View.");
System.out.println("2. Show.");
}
};