如何让这个程序执行,我可以创建一个可以返回选择的循环吗?(你想再试一次吗?)
package javaapplication6;
import java.util.Scanner;
public class JavaApplication6 {
public static void main(String[] args) {
Scanner a=new Scanner(System.in);
int choose;
System.out.println("MENU");
System.out.println("1.Accounts");
System.out.println("2.Age");
System.out.println("3.Balance");
System.out.println("4.Quit");
System.out.println("Enter Selection:");
choose=a.nextInt();
switch(choose){
case 1:
String name,password;
System.out.println("Enter username:");
name=a.nextLine();
if("Nathalie".equals(name))
{
System.out.println("Enter password:");
password=a.nextLine();
if("Dandan".equals(password)){
System.out.println("Welcome "+name+" "+password);
}
else
{
System.out.println("Invalid password");
}
}
else
{
System.out.println("Incorrect Username!");
}
break;
case 2:
String na;
int birthyear,age;
System.out.println("Enter your name");
na=a.nextLine();
System.out.println("Enter your birthyear");
birthyear=a.nextInt();
age=2016-birthyear;
System.out.println(""+na+" your age is "+age);
break;
case 3:
int deposit,withdrawal,balance;
System.out.println("Enter your deposit;");
deposit=a.nextInt();
System.out.println("Enter your withdrawal:");
withdrawal=a.nextInt();
balance=deposit-withdrawal;
if(balance<0){
System.out.println("Your account balance is not enough!");
}
else
{
System.out.println("Your balance is:"+balance);
}
break;
case 4:
System.out.println("Thank you for using this program");
break;
default:
System.out.println("Invalid Selection");
break;
}
}
}
答案 0 :(得分:0)
您可以使用do-while循环。
boolean continue = true;
do {
// your switch statement here:
// Ask for termination: Do you want to contine? y/n
// set continue accordingly
} while(continue );
您的程序将至少执行一次您的开关。询问用户是否要继续并在切换之前跳回。
答案 1 :(得分:0)
虽然用户没有选择退出(在你的代码中,4)。打印选项,让用户再次选择。
do{
//your switch here
}while(choose!= EXIT_CODE);