Getting Keyboard Input

2019-01-04 01:49发布

How do I get simple keyboard input (an integer) from the user in the console in Java? I accomplished this using the java.io.* stuff, but it says it is deprecated.

How should I do it now?

9条回答
Fickle 薄情
2楼-- · 2019-01-04 02:45

Add line:

import java.util.Scanner;

Then create an object of Scanner class:

Scanner s = new Scanner(System.in);

Now you can call any time:

int a = Integer.parseInt(s.nextLine());

This will store integer value from your keyboard.

查看更多
狗以群分
3楼-- · 2019-01-04 02:47

Import: import java.util.Scanner;

Define your variables: String name; int age;

Define your scanner: Scanner scan = new Scanner(System.in);

If you want to type:

  • Text: name = scan.nextLine();
  • Integer: age = scan.nextInt();

Close scanner if no longer needed: scan.close();

查看更多
Luminary・发光体
4楼-- · 2019-01-04 02:51

You can use Scanner class

To Read from Keyboard (Standard Input) You can use Scanner is a class in java.util package.

Scanner package used for obtaining the input of the primitive types like int, double etc. and strings. It is the easiest way to read input in a Java program, though not very efficient.

  1. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream (Keyboard).

For example, this code allows a user to read a number from System.in:

Scanner sc = new Scanner(System.in);
     int i = sc.nextInt();

Some Public methods in Scanner class.

  • hasNext() Returns true if this scanner has another token in its input.
  • nextInt() Scans the next token of the input as an int.
  • nextFloat() Scans the next token of the input as a float.
  • nextLine() Advances this scanner past the current line and returns the input that was skipped.
  • nextDouble() Scans the next token of the input as a double.
  • close() Closes this scanner.

For more details of Public methods in Scanner class.

Exaple:-

import java.util.Scanner;                      //importing class

class ScannerTest {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);       // Scanner object

    System.out.println("Enter your rollno");
    int rollno = sc.nextInt();
    System.out.println("Enter your name");
    String name = sc.next();
    System.out.println("Enter your fee");
    double fee = sc.nextDouble();
    System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
    sc.close();                              // closing object
  }
}
查看更多
登录 后发表回答