Johan Hjalmarsson
Johan Hjalmarsson

Reputation: 3493

simple stdin reading in java

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

Answers (3)

Reimeus
Reimeus

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

jrad
jrad

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

kosa
kosa

Reputation: 66637

args parameter usually contains parameters you pass while running (java className param1) your program

If you want to prompt for input from user, you may consider using Scanner class.

Upvotes: 1

Related Questions