[英]Java stopping do-while loop when user pressed a button
Java新手。 因此,我希望用戶能夠通過鍵入“退出”來隨時停止付款過程。 我該如何實現? 嘗試了do-while循環,但無法正常工作。 這是代碼
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"));
}
您只需按以下步驟更改代碼
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);
因此,您必須執行以下操作:
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);
但是對於cardNo和expiration無效,因為它們是int值,所以您不能輸入“ quit”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.