-
How do you get console input from the keyboard
In C++ it's simple. Just use cin. But I'm trying to get an integer entered at the keyboard and store it in the age variable. Here is what I got but it's not working:
public static void main()
{
int age = 0;
System.out.println("Enter your age: ");
age = System.in;
System.out.println("Your age is " + age);
}
-
Capturing user input is a little more involved in Java than in C++. But just a little. cin has been provided to C++ users to make it easier for us to use formatted content of an input stream. The idea is the same, however, in both languages.
cin is an object of the istream class which, by agreement, is tied to input from the keyboard unless we reassign the source of the stream. It has all of the methods of the istream class. One of those methods is the implementation of an over-ridden ">>" operator, to extract formatted content from the stream. We just need to do a little work in Java to implement the functionality of that over-ridden ">>" operator.
The "in" field of the System class is an InputStream object. You cannot assign an input stream to an int variable. You need to have a method or a class which reads the stream and, if necessary, buffers and/or formats the stream so that you can use it in the manner you're looking for. Look at the Scanner class in the API Documentation - the documentation gives you an example of instantiating an instance of Scanner using the System.in InputStream. You can then use the nextInt() method to return the value you want to assign to age.
Last edited by nspils; 05-23-2007 at 08:10 AM.
-
You can read a character with the simple line:
char a = System.in.read();
2. You can read a string by wrapping the System.in input stream with a BufferedReader:
BufferedReader in = new BufferedReader(
new InputStreamReader( System.in ) );
String input = in.readLine();
Similar Threads
-
Replies: 3
Last Post: 09-05-2002, 06:14 PM
-
By Paula in forum VB Classic
Replies: 10
Last Post: 04-30-2001, 08:20 AM
-
By Paula in forum VB Classic
Replies: 0
Last Post: 04-23-2001, 11:02 AM
-
Replies: 1
Last Post: 02-18-2001, 02:06 PM
-
Replies: 1
Last Post: 01-05-2001, 03:41 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks