在控制台中手动写入的替代方法

Alternative to writing manually in the console

我有一个程序可以扫描写入控制台的输入并给出结果。我怎样才能把这个字符串直接写到我的代码中,这样我就不必在每次尝试这个程序时都在控制台中手动写下它了?我正在使用 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);

    }
}

非常感谢!

你应该在这里使用测试。我建议使用 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);
}