如何从字符串中扫描 "arguments" 并省略空格?

How to scan "arguments" from a String and leave out whitespaces?

我想让用户键入命令(例如:transact fromWallet toWallet 12.00),然后从 Scanner 中获取没有空格的参数,并将它们传递给变量以调用特定方法他们。我仍在研究它,但我设法在没有 Scanner 提供的方法的情况下从 inputString 中提取参数。 Scanner 问题太大了。它要求我进行 5 次输入,而我只需要 4 次,依此类推。 "better way" 是什么?我的解决方案可以吗?我最终是这样做的(请告诉我代码中的 "bad practices"):

CLASS 中的帮助方法:

public static String getNextArg(String s) {
    // get last char
    int cut = s.indexOf(" ");
    if (cut == -1)
        cut = s.length();

    // split arg
    String arg = s.substring(0, cut);

    return arg;
}

public static String getLeftOver(String s) {
    int cut = s.indexOf(" ");
    if (cut == -1)
        cut = s.length() - 1;

    s = s.substring(cut + 1);
    return s;
}

主要的命令部分:

  String cmd = "";
    String arg1, arg2, arg3, arg4;

    System.out.println("Type your command!");
    Scanner cmdScanner = new Scanner(System.in);
    do {
        cmd = cmdScanner.nextLine();

        // Check for "exit"
        if (cmd.length() >= 4)
            if(cmd.substring(0, 4).equalsIgnoreCase("exit"))
                System.exit(0); // Is this a good way to exit a program?

        System.out.println("The args passed to cmd are: ");
        if (!cmd.trim().isEmpty()) {
            arg1 = getNextArg(cmd);
            cmd = getLeftOver(cmd);
            System.out.println("arg1 = " + arg1);
        }
        if (!cmd.trim().isEmpty()) {
            arg2 = getNextArg(cmd);
            cmd = getLeftOver(cmd);
            System.out.println("arg2 = " + arg2);
        }
        if (!cmd.trim().isEmpty()) {
            arg3 = getNextArg(cmd);
            cmd = getLeftOver(cmd);
            System.out.println("arg3 = " + arg3);
        }
        if (!cmd.trim().isEmpty()) {
            arg4 = getNextArg(cmd);
            cmd = getLeftOver(cmd);
            System.out.println("arg4 = " + arg4);
        }
        System.out.println("Type your command!");
    } while (cmdScanner.hasNext());
}

结果符合我的预期。我只想知道如何使用 Scannernext() 方法来做到这一点。这可能会有所帮助,因为稍后我想以适当的方式获得 "next" BigDecimal,并且为所有内容实现自己的方法对于像我这样的菜鸟来说有点过分了。

public static void main(String... obj) {
    try (Scanner scan = new Scanner(System.in)) {
        final Pattern whiteSpace = Pattern.compile("\s+");
        System.out.println("Type your command!");

        do {
            String[] args = whiteSpace.split(scan.nextLine().trim());

            if (args.length == 1 && "exit".equalsIgnoreCase(args[0]))
                return;

            for (int i = 0; i < args.length; i++)
                System.out.println("arg" + (i + 1) + " = " + args[i]);

            System.out.println("Type your command!");
        } while (scan.hasNext());
    }
}