我无法让我的代码返回到代码的开头,并在确认不等于1时重新启动。我已经尝试了返回功能,但它只是重复确认不断,我不知道该怎么做
import java.util.Scanner;
public class zoo {
public static void main(String[] args) {
int optionNumber = 0;
int numberOfTickets = 0;
int confirm = 0;
int totalAmount = 0;
int[] priceArray;
priceArray = new int[3];
priceArray[0] = 18;
priceArray[1] = 36;
priceArray[2] = (int) 32.50;
Scanner input = new Scanner (System.in);
System.out.println("\t" + "@@@@@ Welcome to Zoos Victoria @@@@@");
System.out.println("\t" + "\t" + "MAIN MENU" + "\n");
System.out.println("\t" + "Zoo has the following ticketing options" + "\n");
System.out.println("\t" + "1 = Child (4-6 yrs");
System.out.println("\t" + "2 = Adult (16+ yrs");
System.out.println("\t" + "3 = Senior (60+ yrs" + "\n");
System.out.println("Enter your option:" );
optionNumber=input.nextInt();
if(optionNumber == 1) {
System.out.println("Enter total No of tickets for Child");
numberOfTickets=input.nextInt();
} else if (optionNumber == 2){
System.out.println("Enter total No of tickets for Adult");
numberOfTickets=input.nextInt();
} else {
System.out.println("Enter total No of tickets for Senior");
numberOfTickets=input.nextInt();
}
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
if (confirm ==1) {
System.out.println("confirmed");
} else {
}
if(optionNumber == 1) {
totalAmount=priceArray[0]*numberOfTickets;
System.out.println("Total amount for child tickets: $" + totalAmount);
} else if (optionNumber == 2) {
totalAmount=priceArray[1]*numberOfTickets;
System.out.println("Total amount for adult tickets $" + totalAmount);
} else {
totalAmount=(int) ((double) priceArray[2]*numberOfTickets);
System.out.println("Total amount for senior tickets $" + totalAmount);
}
}
}
答案 0 :(得分:1)
你可以围绕它建立一个循环。像这样的东西(删除了一些代码,但应该清楚它应该是什么样的想法):
boolean chooseOption = true;
while (chooseOption) {
Scanner input = new Scanner(System.in);
//print menu
System.out.println("\t" + "@@@@@ Welcome to Zoos Victoria @@@@@");
//TODO Your code
if (confirm == 1) {
System.out.println("confirmed");
// finish option selection
chooseOption = false;
} else {
//choseOption stays true, hence the menu will be reprinted
System.out.println("Cancelled ticketing." + " Selected Option number: " + optionNumber);
}
}
始终尝试将您的问题转移到许多任务中。在这种情况下,只要没有成功选择,您就想显示一个菜单。
答案 1 :(得分:0)
在检查条件时考虑do...while
循环, with the
例如:
Scanner input = new Scanner(System.in);
int confirm;
do {
// everything in here will repeat
// until the input is not equal to 1
// so put your desired code here
System.out.println("Press 1 to confirm");
confirm = input.nextInt();
} while (confirm != 1);
只要用户未输入{
,do
之后}
以及while
1
之前的所有内容都将重复。