java - 替代在控制台中手动编写
问题描述
我有一个程序可以扫描写在控制台中的输入并给出结果。如何将此字符串直接写入我的代码中,这样我每次尝试程序时都不必在控制台中手动写下它?我正在使用 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);
}
推荐阅读
- python - Python中函数的静态变量是什么?
- html - 像谷歌一样制作按钮动画(涟漪效应)
- regex - Spring Cloud Gateway:在传入请求中重写 URI
- javascript - 如何在我的 React 项目中导入为 JQuery 设计的小部件?
- mongodb - 如何乘以 MongoDB 中 csv 字符串的数量?
- docker - Docker使用套接字组成容器之间没有连接
- python - 为什么我的 Ubuntu Apache 服务器上的 Flask 应用程序得到 ERR_CONNECTION_REFUSED?
- python - 使用 Python Pandas 根据多个条件创建一个名为 df['EV_Sales_Score'] 的列
- ubuntu - 如何匹配文件中的某些单词并列出该匹配单词的所有行?(没有正则表达式)
- flutter - Flutter:未处理的异常:用户拒绝访问设备位置的权限