问题描述
需要复习。我确定我已经知道了这一点,但是我在想办法采取更有效的方法:
简而言之,系统会询问用户要输入多少个输入(最大输入上限)。例如,假设他们说10。 接下来,要求他们输入等于他们要输入的输入数量的个位数整数(在这种情况下,他们将输入10个不同的个位数整数)。
我的问题是我有一段时间没有编码Java了,所以我很生锈。我立即想到了两个选择:
- int输入1 = 0,输入2 = 0,输入3 = 0 ...输入N = 0;
- 使用数组
虽然选项1太过恐怖了,但它可以完成工作。我只是不确定是否有一种更简单的方法可以不使用数组。
import java.util.Scanner;
public class Histogram
{
public static void main(String[] args)
{
//variables
Scanner keyboard = new Scanner(system.in);
int numInputs = 0;
boolean success = false;
//start of program
System.out.println("How many input values [max:20]?");
while (!success)
{
try
{
numInputs = keyboard.nextInt();
numInputChecker(numInputs);
success = true;
}
catch (Exception e)
{
keyboard.nextLine();
System.out.println("Single-digit integers only,please.");
}
}
System.out.println("Enter " + numInputs + " numbers.");
for(int i = 0; i < numInputs; i++)
{
// ?????????
}
}
static void numInputChecker(int integer) throws Exception
{
if ((integer < 1) || (integer > 20))
{
throw new Exception();
}
}
static void numberChecker(int integer) throws Exception
{
if ((integer < 0) || (integer >= 10))
{
throw new Exception();
}
}
}```
解决方法
i)如果使用多个值,则将需要多个变量或某种类型的集合。同意先前关于收藏选择的评论。 (ii)如果所需的重复次数是由计数器控制的,为什么不将循环设置为重复该次数呢?然后,您需要嵌套while循环以确保您的异常处理有效,但是您可以限制输入的数量。 (iii)keyboard.nextInt()可能会出现问题,因为nextInt()不会丢弃'\ n'。最好使用Integer.parseInt(keyboard.nextLine())。 (iv)如果您愿意使用字符串,则只能执行一次I / O,并使用split()和Integer.parseInt()方法来获取必要的值。