How can I get the user input in Java?

2018-12-31 02:52发布

I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.

How can I get the user input in Java?

24条回答
听够珍惜
2楼-- · 2018-12-31 03:44

Use the System class to get the input.

http://fresh2refresh.com/java-tutorial/java-input-output/ :

How data is accepted from keyboard ?

We need three objects,

  1. System.in
  2. InputStreamReader
  3. BufferedReader

    • InputStreamReader and BufferedReader are classes in java.io package.
    • The data is received in the form of bytes from the keyboard by System.in which is an InputStream object.
    • Then the InputStreamReader reads bytes and decodes them into characters.
    • Then finally BufferedReader object reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
InputStreamReader inp = new InputStreamReader(system.in);
BufferedReader br = new BufferedReader(inp);
查看更多
无色无味的生活
3楼-- · 2018-12-31 03:44
Scanner input = new Scanner(System.in);
String inputval = input.next();
查看更多
荒废的爱情
4楼-- · 2018-12-31 03:45

Just one extra detail. If you don't want to risk a memory/resource leak, you should close the scanner stream when you are finished:

myScanner.close();

Note that java 1.7 and later catch this as a compile warning (don't ask how I know that :-)

查看更多
不再属于我。
5楼-- · 2018-12-31 03:47

You can use any of the following options based on the requirements.

Scanner class

import java.util.Scanner; 
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReader and InputStreamReader classes

import java.io.BufferedReader;
import java.io.InputStreamReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(br.readLine());

DataInputStream class

import java.io.DataInputStream;
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader


Console class

import java.io.Console;
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

Apparently, this method does not work well in some IDEs.

查看更多
浮光初槿花落
6楼-- · 2018-12-31 03:48

You can use the Scanner class or the Console class

Console console = System.console();
String input = console.readLine("Enter input:");
查看更多
十年一品温如言
7楼-- · 2018-12-31 03:48

Here is how you can get the keyboard inputs:

Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");  
name = scanner.next(); // Get what the user types.
查看更多
登录 后发表回答