该程序是费用跟踪程序,需要无错误。为了实现该目标,我需要从第11行开始重新启动所有操作。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Size;
int order;
System.out.println("Put in the amount of expenses you have");
Size = sc.nextInt();
System.out.println("put in all your expenses");
int userInput[] = new int[Size];
for (int i = 0; i < userInput.length; i++)
userInput[i] = sc.nextInt();
System.out
.println("do you want it ascending or descending order. If you want it in ascending press 1 or if you want descending press 2");
order = sc.nextInt();
System.out.print("expenses not sorted : ");
printExpenses(userInput);
if (order == 1) {
expensesAscending(userInput);
} else if (order == 2) {
expensedescending(userInput);
}else if (order>2){
//How do i make it so that if they press three or above the program restarts
}
}
答案 0 :(得分:0)
您可以使用永恒循环,直到用户输入有效的条目:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Size;
int order;
int userInput[];
do { // loop starts here
System.out.println("Put in the amount of expenses you have");
Size = sc.nextInt();
System.out.println("put in all your expenses");
userInput = new int[Size];
for (int i = 0; i < userInput.length; i++)
userInput[i] = sc.nextInt();
System.out.println(
"do you want it ascending or descending order. If you want it in ascending press 1 or if you want descending press 2");
order = sc.nextInt();
} while (order < 1 || order > 2); // if the input is not 1 or 2, it goes back
System.out.print("expenses not sorted : ");
printExpenses(userInput);
if (order == 1) {
expensesAscending(userInput);
} else {
expensedescending(userInput);
}
}
但是,如果用户输入错误,我不建议您重新启动整个程序。最好再次询问他输入或他是否要重新启动整个程序。
答案 1 :(得分:0)
在不向您提供代码的情况下,您需要的称为 while循环。 while循环将继续“执行操作”(在这种情况下,尝试使用户输入正确的输入),直到满足条件为止(在这种情况下,order的值为1或2)。
例如:
int order = null;
while (order != 1 && order != 2){
System.out.println("do you want it ascending or descending order."
+ "If you want it in ascending press 1 or if you want descending press 2");
order = sc.nextInt();
}
但是,我也认为您可能需要重新考虑界面设计。错误和不正确的输入处理很重要,但是这使用户可以轻松地在第一次尝试时就正确地做事。例如,用户可能更容易记住如何通过输入“ a”代表升序,输入“ d”代表降序来获得所需的结果。