簡體   English   中英

如何從終端接收輸入並正確使用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM