【问题标题】:Can I input all the command at once?我可以一次输入所有命令吗?
【发布时间】:2017-04-02 13:24:06
【问题描述】:

我用一些方法实现了一个 java 程序。接下来我创建了一个主类,它将通过输入一个单词来调用相关的方法。

例如:

Enter {A|B|C|D|E} to call method. A=method one B = method two...etc
A<--this is the user input
Enter Number:<--the first Scanner input of method A
123<--Input 1
Enter words:<-- the second Scanner input of method A
ABC<--Input 2

123ABC<--The output method A

Enter {A|B|C|D|E} to call method. A=method one B = method two...etc
B<--this is the user input
Enter Number 1:<--the first Scanner input of method B
100<--Input 1
Enter Number 2:<-- the second Scanner input of method B
50<--Input 2

150<--The output method B

Code of Method A {
String output;
private static Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Number:");

String no = keyboard.nextLine();

System.out.println("Enter Words:");

String words = keyboard.nextLine();

//do something...
System.out.println(output);
}

Code of Main class{

private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args){
Main main = new Main();
main.run();
}
  public void run() {
    boolean running = true;

    while (running) {
        displayMenu();

        String command = keyboard.nextLine();
         String[] parts = command.split("^");

        if ("A".equalsIgnoreCase(command)) {
            //call method A
        } else if ("B".equalsIgnoreCase(command)) {
            //call method B
        } else if....etc

        System.out.println();
    }

我想要的是输入
A
123 , ABC
B
100,50 一次
然后系统将为我打印方法 A (123ABC) 和 B (150) 的输出。

我想要的是在“键盘”中输入A,在“no”中输入123,在“words”中输入ABC

我该怎么做?

【问题讨论】:

  • 我希望我的回答对您有所帮助,但您应该在以后提出更具体的问题。您的明确问题是“有可能”,答案是“是”。但是,我们不知道您在实施可行的解决方案时缺少什么,而且您很难找到愿意为您生成整个代码的人。
  • 感谢您的回答。我改变了我的问题,所以它会更具体

标签: java input command


【解决方案1】:

只要您不关闭您的Scanner(或其底层输入流),尚未读取的令牌仍可访问以供以后使用:读取两行(或 4 个令牌 - 逗号是一个)并且“B\n100,50”将保留。

如果您询问如何提供这种输入,这取决于您的调用方法。如果从bash 执行,我会使用以下内容:

echo """A
123 , ABC
B
100,50""" | java ...

如果您询问如何根据名称动态调用方法,请检查反射 API。在我看来,Oracle's tutorial 是一个很好的资源,here's a link 是它关于检索和调用方法的部分。

【讨论】:

    【解决方案2】:

    有两种方法可以做到这一点。

    第一:

    不要直接在控制台中输入,而是先将所有数据输入写入某处,然后将其复制并粘贴到控制台中。


    第二:

    您可以使用hasNexLine()并通过按ctrl+d的键盘发送EOF

    代码:

    public static void main(String[] args) 
        {
    
            Scanner s = new Scanner(System.in);
            StringBuilder sb = new StringBuilder();
    
            while(s.hasNextLine())
            {
                sb.append(s.nextLine());
    
            }
            System.out.println(sb.toString());
        }
    

    提供所有输入并按 ctrl+d 停止输入。

    【讨论】:

    • 第一种方法是我想做的。但它不能保存到方法的输入中。我该如何解决?
    • @Adonis.C 我不明白你在问题中的代码。请发布有效的工作代码。什么是“它无法保存到方法的输入中。我该如何修复它?” 请提供有效的工作代码、您期望的输出(您已经做过)和您得到的输出。 Code of Method ACode of Main class 是什么?以代码的形式提供代码。不是英文的形式。你可以说那里有类似的方法。但是你需要提供准确的代码结构。