Reputation: 3493
I'm just now trying to learn Java and my question is how I read something that the user types?
When I learned C++ the first thing I learned was cin
/cout
but in java I've seen tutorials that talk about GUI before reading user input.
To put it simply, how do I make this program in java:
int main()
{
int foo;
cin >> foo;
cout << foo;
return 0;
}
something like this:
public class foo {
public static void main(String[] args)
{
int foo;
READ FROM IN-BUFFER;
System.out.println(foo);
}
Upvotes: 0
Views: 1126
Reputation: 159754
Would look like:
public class Foo {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int foo = in.nextInt(); // read int from 'STDIN'
System.out.println(foo);
}
}
See more in the Scanner API documentation.
Upvotes: 0
Reputation: 3190
You need to use a Scanner:
import java.util.*;
public class foo {
public static void main(String[] args) {
int foo;
Scanner scnr = new Scanner(System.in);
foo = scnr.nextInt();
System.out.println(foo);
}
}
Here, the Scanner reads input from System.in (the keyboard), then assigns the value of the input to foo. If the input is not an int, an exception will occur.
Upvotes: 3