首页 > 解决方案 > 替代在控制台中手动编写

问题描述

我有一个程序可以扫描写在控制台中的输入并给出结果。如何将此字符串直接写入我的代码中,这样我每次尝试程序时都不必在控制台中手动写下它?我正在使用 java.util.Scanner 进行扫描。

现在我正在运行测试器并在控制台中输入 4 个单词。然后程序给了我想要的结果。如何自动化打字部分?

import java.util.Scanner;
import java.io.PrintStream;

public class B6A4_Interpreter {
    public static void eingabe(Scanner sc, PrintStream ps) {
        String position ="";
        String zeichen = "";
        String in = "";
        String satz = "";
        String Ergebnis = "";
        int count = 0;
        while (count < 4) {
            position = sc.next();
            zeichen = sc.next();
            in = sc.next();
            satz = sc.next();
            count = 4;
        }
        sc.close();
        if (position.equals("nach") && (satz.length() != 0)) {
            Ergebnis = satz.substring(satz.indexOf(zeichen)+1);
        }
        else if (position.equals("nach") && (satz.length() == 0)) {
            Ergebnis = "Zeichenfolge";
        }
        else if (position.equals("vor") && (satz.length() != 0)) {
            Ergebnis = satz.substring(0,satz.lastIndexOf(zeichen));
        }
        else if (position.equals("vor") && (satz.length() == 0)) {
            Ergebnis = "";
        }
        ps.println(Ergebnis);
    }
}

测试人员:

import java.io.InputStream;
import java.util.Scanner;


public class Test_B6A4 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        B6A4_Interpreter.eingabe(sc, System.out);

    }
}

非常感谢!

标签: javajava.util.scanner

解决方案


你应该在这里使用测试。我建议使用 JUnit5。但如果你不想这样做,你可以手动填充扫描仪:

public static void main(String[] args) {
        Scanner sc = new Scanner("FirstItem SecondItem ThirdItem FourthItem");
        B6A4_Interpreter.eingabe(sc, System.out);
}

如果你想有空格的值,你可以为例如新行设置分隔符:

public static void main(String[] args) {
        Scanner sc = new Scanner("First Item\nSecond Item\nThird Item\nFourthItem");
        sc.useDelimiter(Pattern.compile("(\\n)|;"));
        B6A4_Interpreter.eingabe(sc, System.out);
}

推荐阅读