Reputation: 698
As a user I type following command into the java console:
!login <Username> <udpPort>
so, i.e.
!login Bob 2233
What I need is to easily get the values from this input:
String username = "Bob";
int port = 2233;
I am using a BufferedReader to get the input.
I already tried: But of course this is not working. But thats what I would like to have:
String [] input = in.readReadLine(); //ofcourse this is not working
Then I can easily assign the values:
String username = input[2]; //save "Bob"
int port = Integer.parseInt(input[3]); //save 2233
Any advices appreciated, Dave
Upvotes: 1
Views: 8539
Reputation: 111
Scanner class is best suited for taking input from console.
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);
}
}
This is a simple class demonstrating the use of Scanner class in Java. It has several method that can help you in reading different types of inputs for ex- int
, char
, String
, etc.
Upvotes: 2
Reputation: 34367
I think you can use java.util.Scanner
as below:
Scanner inputScanner = new Scanner(System.in);
inputScanner.next(); //reads whole word
inputScanner.nextInt(); //reads whole numeral
inputScanner.nextLine(); //reads whole line
Now using nextLine
, read the line and split
String line = inputScanner.nextLine();
String[] commands = line.split(" "); //splits space delimited words in the line
or using next()
, read one command at time e.g.
command[0] = inputScanner.next();
command[1] = inputScanner.next();
Or you can use next()
and nextInt()
String username = inputScanner.next(); //save "Bob"
int port = inputScanner.nextInt(); //save 2233
More method details here. Scanner
Upvotes: 0
Reputation: 51030
You should do
String [] input = in.readReadLine().split("\\s+"); // split the line at spaces
And use index 1 and 2 because array index starts from 0 not 1
String username = input[1]; //get the second element of the array
int port = Integer.parseInt(input[2]); //get the third element and parse
Upvotes: 0
Reputation: 66637
BufferedReaeder
readLine() method return String
.
Once you get String, you need to either Split();
(or) StringTokenizer
to get as separate Strings.
Upvotes: 3