我想创建一个菜单程序,有不同的选项:
1)Enter Name
2)Display Name
3)Change Name
4)Quit
但出于某种原因,我无法获得用于在Q1中存储名称的变量,以便在Q2中使用!
这里是代码:(错误发生在案例2中,变量full_name带下划线红色且不起作用)
package Testing;
import java.util.Scanner ;
public class Menu {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
// print menu
for (int i = 1; i <= 5; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
// handle user commands
boolean quit = false;
int menuItem;
do {
System.out.print("Choose menu item: ");
menuItem = in.nextInt();
switch (menuItem) {
case 1:
System.out.println("You've chosen item #1");
{
Scanner user_input = new Scanner(System.in);
String first_name;
System.out.print("Enter your first name: ");
first_name = user_input.next( );
String family_name;
System.out.print("Enter your family name: ");
family_name = user_input.next( );
String full_name;
full_name = first_name + " " + family_name;
System.out.println("You are " + full_name);
}
break;
case 2:
System.out.println("You've chosen item #2");
System.out.println("You are " + full_name);
break;
case 3:
System.out.println("You've chosen item #3");
// do something...
break;
case 4:
System.out.println("You've chosen item #4");
// do something...
break;
case 5:
System.out.println("You've chosen item #5");
// do something...
break;
case 0:
quit = true;
break;
default:
System.out.println("Invalid choice.");
}
} while (!quit);
System.out.println("Bye-bye!");
}
}
答案 0 :(得分:1)
你应该将full_name
置于循环之外,因为它当前位于本地范围内,而其他案例陈述是无法访问的。
答案 1 :(得分:0)
import java.util.Scanner ;
public class Menu {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
// print menu
for (int i = 1; i <= 5; i++)
System.out.println(i + ". Menu item #" + i);
System.out.println("0. Quit");
// handle user commands
//The name
String first_name = "";
String family_name = "";
String full_name = "";
while(true) {
System.out.print("Choose menu item: ");
int menuItem = 0;
try { // If you enter a string it will throw an exception!
menuItem = in.nextInt();
} catch(Exception e) {
System.out.println(e.getMessage());
}
switch (menuItem) {
case 1:
System.out.println("You've chosen item #1");
System.out.print("Enter your first name: ");
first_name = in.next( );
System.out.print("Enter your family name: ");
family_name = in.next( );
full_name = first_name + " " + family_name;
System.out.println("You are " + full_name);
break;
case 2:
System.out.println("You've chosen item #2");
System.out.println("You are " + full_name);
break;
case 3:
System.out.println("You've chosen item #3");
// do something...
break;
case 4:
System.out.println("You've chosen item #4");
// do something...
break;
case 5:
System.out.println("You've chosen item #5");
// do something...
break;
case 0:
System.out.println("bye-bye");
System.exit(0); // Exit
break;
default:
System.out.println("Invalid choice.");
}
}
}
}