1,105,644 Community Members

Input...

Member Avatar
jackmaverick1
Posting Whiz in Training
228 posts since May 2010
Reputation Points: -4 [?]
Q&As Helped to Solve: 12 [?]
Skill Endorsements: 0 [?]
 
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

Member Avatar
JamesCherrill
... trying to help
10,387 posts since Apr 2008
Reputation Points: 2,081 [?]
Q&As Helped to Solve: 1,752 [?]
Skill Endorsements: 47 [?]
Moderator
Featured
 
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
Member Avatar
jackmaverick1
Posting Whiz in Training
228 posts since May 2010
Reputation Points: -4 [?]
Q&As Helped to Solve: 12 [?]
Skill Endorsements: 0 [?]
 
0
 

Thank you, that worked perfectly

Member Avatar
sourabh17
Newbie Poster
19 posts since Mar 2011
Reputation Points: -1 [?]
Q&As Helped to Solve: 3 [?]
Skill Endorsements: 0 [?]
 
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: