简体   繁体   中英

Java stopping do-while loop when user pressed a button

new to Java. So I want the user to be able to stop the payment process anytime they want to by typing "quit". How can I achieve that? Tried the do-while loop but its not working. Here is the code

  public void payItems() {
    Scanner s = new Scanner(System.in);
    String word;
    do {
        System.out.println("Enter name: ");
        String name = s.next();
        s.nextLine();
        //where should I put word = s.next
        System.out.println("Enter address: ");
        String address = s.nextLine();
        System.out.println("Enter card number: ");
        int cardNo = s.nextInt();
        System.out.println("Enter card expiration date: (DDMMYY)");
        int expirationDate = s.nextInt();
        Customer newcust = new Customer(name, address, cardNo, expirationDate);
    } while (!word.equals("quit"));
}

Simply you can change your code as follows

 boolean status=true;
    do {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter name: ");
        String name = s.nextLine();
        System.out.println("Enter address: ");
        String address = s.nextLine();
        System.out.println("Enter card number: ");
        int cardNo = s.nextInt();
        System.out.println("Enter card expiration date: (DDMMYY)");
        int expirationDate = s.nextInt();
        System.out.println("You want to add more or quit(type continue to add another, type quit to exit): ");
        String word=s.next();
        if(word.equals("quit")){
            status=false;
        }
    } while (status);

So you have to do somethink like this:

Scanner s = new Scanner(System.in);
System.out.println("Enter name: ");
String name = s.next();
s.nextLine();
if (name.equals("quit") 
   return;
//where should I put word = s.next
System.out.println("Enter address: ");
String address = s.nextLine();
if (address.equals("quit") 
   return;
System.out.println("Enter card number: ");
int cardNo = s.nextInt();
System.out.println("Enter card expiration date: (DDMMYY)");
int expirationDate = s.nextInt();
Customer newcust = new Customer(name, address, cardNo, expirationDate);

but it doesnt work for cardNo and expiration because these are int values, so you can not enter "quit".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM