gpt4 book ai didi

java - 如果用户输入无效代码如何编码?

转载 作者:行者123 更新时间:2023-12-02 10:15:11 25 4
gpt4 key购买 nike

如果用户输入无效代码,则显示您选择了无效选项并将价格设置为 0。

import java.util.Scanner;
public class ShadyRestRoom {

public static void main(String[]args) {
Scanner scanner= new Scanner(System.in);
int QueenBed = 125;
int KingBed = 139;
int KingPullout = 165;

System.out.println("Choose: 1 for a Queen bed Choose: 2 for a King bed or Choose: 3 for a King bed with a pullout couch");
int RoomChoice= scanner.nextInt();

if (RoomChoice == 1)
System.out.println("$125 for a Queen bed");
if (RoomChoice == 2)
System.out.println("$139 for a King bed");
if (RoomChoice == 3)
System.out.println("$165 for a King bed with a pullout couch");

while (RoomChoice == 4)
System.out.println("ERROR Please enter a valid Choice");
RoomChoice = scanner.nextInt();
if (RoomChoice == 8)
System.out.println("ERROR Please enter a valid Choice");
RoomChoice = scanner.nextInt();
}
}

我似乎不知道如何设置它,所以它确实=(如果用户输入无效代码,则显示您选择了无效选项并将价格设置为 0。)

最佳答案

完成选择的一种方法是 switch 语句。它就是为此而生的。因此,选择需要转变。

现在,在 switch 中,每个有效选择都有一个“case”语句。此外,最后没有明确提到的所有其他内容都有一个“默认”。

您可以使用该默认值来“作弊”,并将变量重置为您选择的定义值。

现在,循环中的条件再次变得更简单,因为它不再那么模糊(“一些输入除外......”),但只有一个定义的值表示“另一个循环”。

我将“-1”作为指示符,表示“出了问题”。但是您可以使用任何对您有意义的内容作为“转义”(这就是这些值的名称:-1 是“转义代码”)。因此, while 检查我的转义“-1”并继续询问,直到用户给出范围内的内容。

public static class ShadyRestRoom {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int QueenBed = 125;
int KingBed = 139;
int KingPullout = 165;
int RoomChoice = -1;
do {
System.out.println("Choose: 1 for a Queen bed Choose: 2 for a King bed or Choose: 3 for a King bed with a pullout couch");
RoomChoice = scanner.nextInt();
switch (RoomChoice) {
case 1:
System.out.println("$125 for a Queen bed");
break;
case 2:
System.out.println("$139 for a King bed");
break;
case 3:
System.out.println("$165 for a King bed with a pullout couch");
break;
//you can also explicitely take a group of numbers that need to be treated the same way:
case 4:
case 8:
default: //this is the default for everything that wasn't metioned before
RoomChoice = -1;
System.out.println("ERROR Please enter a valid Choice");
}
} while (-1 == RoomChoice);

}
}

顺便说一句:变量使用小写字母是一种约定。所以“roomChoice”而不是“RoomChoice”会更好。这样您就可以立即看到这是一个变量而不是类。

关于java - 如果用户输入无效代码如何编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54739729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com