0

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);
    }
4

3 に答える 3

3

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.

于 2012-07-26T19:16:40.853 に答える
1

argsパラメータには通常、プログラムの実行中に渡すパラメータ(java className param1)が含まれます

ユーザーからの入力を求める場合は、Scannerクラスの使用を検討してください。

于 2012-07-26T19:16:15.127 に答える
0

次のようになります:

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);
    }
 }

詳細については、ScannerAPIのドキュメントをご覧ください。

于 2012-07-26T19:16:16.377 に答える