问题描述
程序的这一部分要求用户输入所需的饮料数量,如果饮料数量为负数,则必须返回“无效数量”。
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
is probably the most straightforward)中。
<!-- How can I refresh below div every x seconds? -->
<div>
<?php if (isset($lmt)) { ?>
<p>Last modified by <?= $lmt['fname']; ?> at <?= $lmt['ts']; ?></p>
<?php } ?>
</div>