【问题标题】:Java: How to get values from console input easilyJava:如何轻松地从控制台输入中获取值
【发布时间】:2012-10-23 03:49:30
【问题描述】:

作为用户,我在 java 控制台中输入以下命令:

!login <Username> <udpPort>

所以,即

!login Bob 2233

我需要的是轻松地从此输入中获取值:

String username = "Bob";
int port = 2233;

我正在使用 BufferedReader 来获取输入。

我已经尝试过:但这当然行不通。但这就是我想要的:

String [] input = in.readReadLine(); //ofcourse this is not working

然后我可以轻松地分配值:

String username = input[2]; //save "Bob"
int port = Integer.parseInt(input[3]); //save 2233

任何建议表示赞赏, 戴夫

【问题讨论】:

标签: java string console split readline


【解决方案1】:

BufferedReaederreadLine() 方法返回String

获得字符串后,您需要Split();(或)StringTokenizer 才能获得单独的字符串。

【讨论】:

  • 是的。我只是用这个: String[] sI = in.readLine().split(" ");
【解决方案2】:

Scanner 类最适合从控制台获取输入。

import java.util.*;

public class ConsoleInput { 
    public static void main(String[] args) {
        Scanner scanInput = new Scanner(System.in);
        String input = scanInput.nextLine();
        System.out.println("The input is : "+ input);  
    }  
}

这是一个简单的类,演示了 Java 中 Scanner 类的使用。它有几种方法可以帮助您读取不同类型的输入,例如 intcharString 等。

【讨论】:

    【解决方案3】:

    你应该这样做

    String [] input = in.readReadLine().split("\\s+"); // split the line at spaces
    

    并使用索引 1 和 2,因为数组索引从 0 而不是 1 开始

    String username = input[1]; //get the second element of the array
    int port = Integer.parseInt(input[2]); //get the third element and parse
    

    【讨论】:

      【解决方案4】:

      我认为你可以使用java.util.Scanner,如下所示:

        Scanner inputScanner = new Scanner(System.in);
        inputScanner.next(); //reads whole word
        inputScanner.nextInt(); //reads whole numeral
        inputScanner.nextLine(); //reads whole line
      

      现在使用nextLine,读取该行并拆分

         String line = inputScanner.nextLine();
         String[] commands = line.split(" "); //splits space delimited words in the line
      

      或使用next(),一次读取一个命令,例如

        command[0] = inputScanner.next(); 
        command[1] = inputScanner.next(); 
      

      或者你可以使用next()nextInt()

        String username = inputScanner.next();  //save "Bob"
        int port = inputScanner.nextInt(); //save 2233
      

      更多方法细节在这里。 Scanner

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多