如何获得Java中的用户输入

如何获得Java中的用户输入

本文介绍了如何获得Java中的用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个计算器,但是由于我不知道如何获取用户输入,所以无法使其正常工作.

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

如何获取Java中的用户输入?

How can I get the user input in Java?

推荐答案

您可以根据需要使用以下任何选项.

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

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


BufferedReader InputStreamReader


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(s);


DataInputStream


DataInputStream class

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

DataInputStream类中的readLine方法已被弃用.要获取String值,您应该将先前的解决方案与BufferedReader结合使用

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

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

显然,此方法在某些IDE中不能很好地工作.

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

这篇关于如何获得Java中的用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:39