如何从字符串中扫描“参数”并省略空格?

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


课堂上的帮助方法:


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());

}

结果符合我的预期。我只想知道如何使用Scanner'snext()方法来做到这一点。这可能会有所帮助,因为稍后我想以适当的方式获得“下一个” BigDecimal,并且对于像我这样的菜鸟来说,为所有事情实现自己的方法会有点多。


四季花海
浏览 91回答 1
1回答

明月笑刀无情

public static void main(String... obj) {&nbsp; &nbsp; try (Scanner scan = new Scanner(System.in)) {&nbsp; &nbsp; &nbsp; &nbsp; final Pattern whiteSpace = Pattern.compile("\\s+");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Type your command!");&nbsp; &nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String[] args = whiteSpace.split(scan.nextLine().trim());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (args.length == 1 && "exit".equalsIgnoreCase(args[0]))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < args.length; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("arg" + (i + 1) + " = " + args[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Type your command!");&nbsp; &nbsp; &nbsp; &nbsp; } while (scan.hasNext());&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java