[英]How can I receive an input from my Terminal and use it properly
我的任务是通过终端接收“插入号码”之类的命令,并使用该号码调用insert方法。
我的方法正在工作。 这是我的代码段:
String command = Terminal.readLine();
while (command != null) {
switch (command) {
case "insert number":
String[] split = command.split(" ");
linkedTuple.insert(Integer.parseInt(split[1]));
break;
仅是我完整代码的一部分。 我的问题是,如果我使用大小写“ insert number”,它只有在我真的会在终端中写插入号的情况下才起作用,但是我想写例如insert 3来插入数字3,但是如何在我的开关盒中调用它? 我的终端机正在工作,因为诸如quit之类的命令正在退出我的应用程序。
谢谢!
编辑:为清楚起见,我的主要方法是:
public static void main(String[] args) {
int[] tuple = { 1 };
LinkedNaturalNumberTuple linkedTuple = new LinkedNaturalNumberTuple(
tuple);
String command = Terminal.readLine();
String[] split = command.split(" ");
while (command != null) {
switch (split[0]) {
case "insert":
linkedTuple.insert(Integer.parseInt(split[1]));
break;
case "remove":
Terminal.printLine(""
+ linkedTuple.remove(Integer.parseInt(split[1])));
break;
case "swap":
if (!linkedTuple.swap(Integer.parseInt(split[1]),
Integer.parseInt(split[2]))) {
Terminal.printLine("Error, your numbers are invalid please try again!");
}
break;
case "min":
if (linkedTuple.min() == -1) {
Terminal.printLine("Error, your tuple is empty, use insert number to insert a number!");
} else {
Terminal.printLine("" + linkedTuple.min());
}
break;
case "max":
if (linkedTuple.max() == -1) {
Terminal.printLine("Error, your tuple is empty, use insert number to insert a number!");
} else {
Terminal.printLine("" + linkedTuple.max());
}
break;
case "info":
Terminal.printLine(linkedTuple.toString());
break;
case "quit":
System.exit(1);
break;
}
command = Terminal.readLine();
}
}
如果我输入了一个命令,然后又想输入另一个命令,则第一个命令将被调用。 例如:信息,然后打印我的元组插入3我的元组被打印退出我的元组被打印等等
使用类似:
String[] array = "insert number".split(" ");
....
switch (array[0]) {
case "insert":
除上述内容外,您还需要交换以下语句的顺序:
String command = Terminal.readLine();
String[] split = command.split(" ");
while (command != null) {
至
String command = Terminal.readLine();
String[] split;
while (command != null) {
command = Terminal.readLine();
split = command.split(" ");
这样您就可以循环进入并每次都要求用户输入,并从用户输入的新命令中分离出来。
编辑后回答:
在循环结束时,
command = Terminal.readLine();
但是,您无需拆分新命令。 结果,您的switch语句仍然查看旧的拆分。
因此,您需要将循环的结尾更改为:
command = Terminal.readLine();
split = command.split(" ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.