![](/img/trans.png)
[英]More efficient way to do if/else branch with variable assignment in Java
[英](JAVA) Is there a more efficient way to do this?
我程序的这部分要求用户输入他们想要的饮料数量,如果饮料数量为负数,它必须返回“无效数量”。
System.out.print("Please enter the number of each drink that you like to purchase:");
System.out.println();
System.out.print("Small Coffee: ");
int smallCoffee = scnr.nextInt();
if (smallCoffee < 0) {
System.out.println("Invalid amount")
System.exit(1);
}
System.out.print("Medium Coffee: ");
int mediumCoffee = scnr.nextInt();
System.out.print("Large Coffee: ");
int largeCoffee = scnr.nextInt();
System.out.print("Banana Berry Smoothie: ");
int berrySmoothie = scnr.nextInt();
System.out.print("Mocha Shake: ");
int mochaShake = scnr.nextInt();
System.out.print("Raspberry Green Tea: ");
int greenTea = scnr.nextInt();
除了在每个选项下放置 if 语句之外,还有其他方法可以在每个选项下输出“无效金额”吗?
方法,当然。 你有一个任务:
向用户询问一个非负数。
因此,编写一个封装作业的方法:
public int getAmount(Scanner scanner, String prompt) {
while (true) {
System.out.println(prompt);
int v = scanner.nextInt();
if (v >= 0) return v;
System.out.println("Please enter positive numbers only.");
}
}
请注意您现在如何写“如果他们搞砸了,再问一次,而不是直接退出”,然后根据需要多次重复使用。
@rzwitserloot 建议编写一种方法来封装输入的任务,这是最直接,也可能是最“正确”的方法。
但是,如果您出于某种原因确实不想编写另一个函数,则可以使变量名动态化! 将它们写成一个字符串列表,遍历这些字符串,并将它们存储在一个数据结构中( Map
可能是最直接的)。
Map<String, Integer> variables = new HashMap<>();
String[] variableNames = {
"Small Coffee",
"Medium Coffee",
"Large Coffee",
"Banana Berry Smoothie",
"Mocha Shake",
"Raspberry Green Tea"
};
System.out.println("Please enter the number of each drink that you like to purchase:");
for (String drinkName : variableNames) {
// ask for the amount of drink
System.out.print(drinkName + ": ");
int amount = scnr.nextInt();
// error check
if (amount < 0) {
System.out.println("Invalid amount");
System.exit(1);
}
// add to map
variables.put(drinkName, amount);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.