AJR
AJR

Reputation: 589

stdin Java Input

I am having problems with STDIN

I would to read the following 2 string, for example:

Input:

abc

xyz

When typing "abc", then press Enter, I get abc back. However i dont want that. I would like to type another string just like input above.

So what want is: Type abc, Enter, type xyz enter

here is my code:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s; 
while ((s = in.readLine()) != null && s.length() != 0){     
      System.out.println(s);
}

Thanks

Upvotes: 0

Views: 1999

Answers (2)

J Atkin
J Atkin

Reputation: 3140

Scanner is the preferred way to get input from the console. Example:

Scanner in = new Scanner(System.in);
System.out.print("Please enter a string: ");
String input = in.nextLine();

System.out.println("You entered: \"" + input + "\"");

Scanner also has other useful methods like nextInt and nextChar. Full docs on Scanner

Upvotes: 0

rodit
rodit

Reputation: 1766

You should use Scanners for this.

Here is an example implementing scanners:

Scanner scanner = new Scanner(System.in);

String s = scanner.nextLine();
String s2 = scanner.nextLine();

System.out.println(s + ":" + s2);

//Close scanner when finished with it:
scanner.close();

Here is the full documentation for further reading and examples: Oracle documentaion

Upvotes: 1

Related Questions