1.11M Members

Input...

 
0
 

Hi, I'm very new to Java (started today, though I have 1.5 years in c++) and I've now read a little bit about Java, the thing that I can't find is how to take user input from the keyboard through a console window... How can you go about do that?

I'm looking for something like std::cin in c++. That however doesn't seem to be available in Java.

Thanks,
jt

 
0
 

Yup. System.in is the console input stream.
It's common practice to use this with the Scanner class to handle some basic parsing of the input...

Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
or...
int i = sc.nextInt(); // etc etc - see API doc for details of all options
 
0
 

Thank you, that worked perfectly

 
0
 

You can also use the BufferedReader class beside the Scanner class, check j2se tutorial for reading user input for better understanding...

import java.io.*;

public class GetUserInput
{
	public static void main( String [] args )
	{	
		String str = null;
		
		BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
		
		System.out.println( "Enter whatever :: " );

		try 
		{
			str = br.readLine();
		}
		
		catch( IOException exp )
		{
			System.err.println( exp.getMessage() );
		}
		System.out.println( str );
	}
}
Question Answered as of 3 Years Ago by JamesCherrill and sourabh17
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: