首页 > 解决方案 > 控制台上的 Java 模拟扫描仪输入因多个输入而失败

问题描述

我正在尝试借助 Scanner 在 Java 控制台中模拟多个输入。我需要它们进行单元测试,但它失败的只有前几个值被正确采用,但其余的被忽略。请看下面的代码

String simulatedInput = "1\n" + "2\n" + "James\n" + "Snow\n" + "5\n" + "Mango\n" + "6\n";
InputStream in = new ByteArrayInputStream(simulatedInput.getBytes());
Scanner scanner = new Scanner(in);
int index = 0;
if (scanner.hasNextInt()) {
    index = scanner.nextInt();
}
if (index != 1) {
    System.out.println("#1) Should be 1");
}

if (scanner.hasNextInt()) {
    index = scanner.nextInt();
}

if (index != 2) {
    System.out.println("#2) Should be 2");
}
index = -1;
String value = null;
if (scanner.hasNextLine()) {
    value = scanner.nextLine();
}
if (!"James".equals(value)) {
    System.out.println("#3) Should be 'James' but |" + value + "|");
}
if (scanner.hasNextLine()) {
    value = scanner.nextLine();
}
if (!"Snow".equals(value)) {
    System.out.println("#4) Should be 'Snow' but |" + value + "|");
}

if (scanner.hasNextInt()) {
    index = scanner.nextInt();
}
if (index != 5) {
    System.out.println("#5) Should be 5 but " + index);
}

if (scanner.hasNextLine()) {
    value = scanner.nextLine();
}
if (!"Mango".equals(value)) {
    System.out.println("#6) Should be 'Mango' but |" + value + "|");
}

if (scanner.hasNextInt()) {
    index = scanner.nextInt();
}
if (index != 6) {
    System.out.println("#7) Should be 6 but " + index);
}

System.out.println("*** There should be the only line ***");

结果如下,测试# 1 和 2 通过,但其余部分因预期的输入而失败James

#3) Should be 'James' but ||
#4) Should be 'Snow' but |James|
#5) Should be 5 but -1
#6) Should be 'Mango' but |Snow|
#7) Should be 6 but 5
*** There should be the only line ***

请注意,我无法更改代码,因为我正在对该代码进行单元测试,所以我只能更改我的模拟输入。这可以解决吗?

对可能重复的响应

这不是重复的问题,我无法更改代码以消耗额外的 \n,我只能在模拟输入中进行更改。

标签: javajava.util.scannersystem.in

解决方案


推荐阅读