Java help for restart program

天大地大妈咪最大 提交于 2019-12-20 07:13:33

问题


import java.util.Scanner ;

public class Mal { 

    public static void main (String []args) {

        System.out.println("Welcome") ;
        Scanner myinput=new Scanner (System.in) ;
        System.out.println("Make your choice. \n 1.Check a card number \n 2.Quit.");
        int choise=myinput.nextInt();
        switch(choise) {
            case 1:System.out.println("Enter your credit card number: ");
            break;
            case 2:System.out.println("Are you sure?") ;
            String answer=myinput.next();

            if(answer.equals("yes")){
                System.out.println("Byee :)") ;
                System.exit(0);
            }
            break;
            default: System.out.println("Idiot!") ;
            break;
        }
    }       
}

i want a program which starts again if user types something different than "yes"


回答1:


Here's what you can do

have a flag like this

boolean quit = false;

and a while enclosing your options

while(!quit){
...
...
}

and

set quit = true if the user wants to quit.

EDIT:

Something like this

public static void main(String a[]) {
    System.out.println("Welcome");
    Scanner myinput = new Scanner(System.in);
    boolean quit = false;
    while (!quit) {
        System.out
                .println("Make your choise. \n 1.Check a card number \n 2.Quit.");
        int choise = myinput.nextInt();
        switch (choise) {
        case 1:
            System.out.println("Enter your credit card number: ");
            break;
        case 2:
            System.out.println("Are you sure?");
            String answer = myinput.next();

            if (answer.equals("yes")) {
                System.out.println("Byee :)");
                quit= true;
            }
            break;
        default:
            System.out.println("Idiot!");
            break;
        }
    }


来源:https://stackoverflow.com/questions/5494690/java-help-for-restart-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!