【发布时间】:2011-07-14 08:07:32
【问题描述】:
我试图创建一个计算器,但我无法让它工作,因为我不知道如何获取用户输入。
如何在 Java 中获取用户输入?
【问题讨论】:
-
呃,你的问题是什么?您刚刚发布了一些代码并说您不喜欢指针。如果您不了解按引用传递和按值传递,不了解指针仍然会在 java 中反噬您。
-
你应该尝试学习java 读一本书,Java How to Program,7/e 不错
我试图创建一个计算器,但我无法让它工作,因为我不知道如何获取用户输入。
如何在 Java 中获取用户输入?
【问题讨论】:
最简单的方法之一是使用Scanner 对象,如下所示:
import java.util.Scanner;
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();
【讨论】:
Scanner reader1 = new Scanner(System.in);重新打开吗?
您可以根据要求使用以下任何选项。
Scanner类import java.util.Scanner;
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
BufferedReader 和 InputStreamReader 类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类import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
DataInputStream 类中的readLine 方法已弃用。要获取 String 值,您应该使用以前的解决方案与 BufferedReader
Console类
import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
显然,这种方法在某些 IDE 中效果不佳。
【讨论】:
DataInputStream 用于读取二进制数据。在System.in 上使用readInt 不会从字符数据中解析整数,而是会重新解释unicode 值并返回无意义的值。详情见DataInput#readInt(DataInputStream实现DataInput)。
您可以使用Scanner 类或控制台类
Console console = System.console();
String input = console.readLine("Enter input:");
【讨论】:
您可以使用BufferedReader 获取用户输入。
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.println("Enter your Account number: ");
accStr = br.readLine();
它将在accStr 中存储String 值,因此您必须使用Integer.parseInt 将其解析为int。
int accInt = Integer.parseInt(accStr);
【讨论】:
以下是获取键盘输入的方法:
Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");
String name = scanner.next(); // Get what the user types.
【讨论】:
最好的两个选项是BufferedReader 和Scanner。
使用最广泛的方法是Scanner,我个人更喜欢它,因为它简单易实现,以及将文本解析为原始数据的强大实用性。
使用扫描仪的优势
Scanner 类易于使用BufferedInputStream 的优点
Scanner between threads)总的来说,每种输入法都有不同的用途。
如果您输入大量数据BufferedReader 可能
对你更好
如果您输入大量数字 Scanner 会自动解析
很方便
对于更多基本用途,我推荐Scanner,因为它更易于使用且更易于编写程序。下面是一个如何创建Scanner 的快速示例。我将在下面提供一个全面的示例,说明如何使用Scanner
Scanner scanner = new Scanner (System.in); // create scanner
System.out.print("Enter your name"); // prompt user
name = scanner.next(); // get user input
(有关BufferedReader 的更多信息,请参阅How to use a BufferedReader 和Reading lines of Chars)
import java.util.InputMismatchException; // import the exception catching class
import java.util.Scanner; // import the scanner class
public class RunScanner {
// main method which will run your program
public static void main(String args[]) {
// create your new scanner
// Note: since scanner is opened to "System.in" closing it will close "System.in".
// Do not close scanner until you no longer want to use it at all.
Scanner scanner = new Scanner(System.in);
// PROMPT THE USER
// Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
System.out.println("Please enter a number");
// use "try" to catch invalid inputs
try {
// get integer with "nextInt()"
int n = scanner.nextInt();
System.out.println("Please enter a decimal"); // PROMPT
// get decimal with "nextFloat()"
float f = scanner.nextFloat();
System.out.println("Please enter a word"); // PROMPT
// get single word with "next()"
String s = scanner.next();
// ---- Note: Scanner.nextInt() does not consume a nextLine character /n
// ---- In order to read a new line we first need to clear the current nextLine by reading it:
scanner.nextLine();
// ----
System.out.println("Please enter a line"); // PROMPT
// get line with "nextLine()"
String l = scanner.nextLine();
// do something with the input
System.out.println("The number entered was: " + n);
System.out.println("The decimal entered was: " + f);
System.out.println("The word entered was: " + s);
System.out.println("The line entered was: " + l);
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input entered. Please enter the specified input");
}
scanner.close(); // close the scanner so it doesn't leak
}
}
注意:Console 和 DataInputStream 等其他类也是可行的替代方案。
Console 具有一些强大的功能,例如读取密码的能力,但是并非在所有 IDE(例如 Eclipse)中都可用。发生这种情况的原因是因为 Eclipse 将您的应用程序作为后台进程而不是作为具有系统控制台的顶级进程运行。 Here is a link 是一个关于如何实现 Console 类的有用示例。
DataInputStream 主要用于以与机器无关的方式从底层输入流中读取作为原始数据类型的输入。 DataInputStream 通常用于读取二进制数据。它还提供了读取某些数据类型的便捷方法。例如,它有一个读取 UTF 字符串的方法,其中可以包含任意数量的行。
但是,它是一个更复杂的类并且难以实现,因此不建议初学者使用。 Here is a link 是一个有用的例子,如何实现DataInputStream。
【讨论】:
DataInputStream——那里的描述听起来与Scanner 的用例相同:将数据读入原语。此外,如果有人处于不知道如何获取用户输入的阶段,他们很可能也不明白为什么标准库的某些部分在某些 IDE 中不可用。对我来说当然是这样——为什么Console 不可用?
try-with-resource 会更好。
您可以编写一个简单的程序来询问用户的姓名并打印回复使用的输入内容。
或者要求用户输入两个数字,您可以对这些数字进行加、乘、减或除,然后打印用户输入的答案,就像计算器的行为一样。
所以你需要 Scanner 类。你必须import java.util.Scanner; 并且在你需要使用的代码中
Scanner input = new Scanner(System.in);
输入是一个变量名。
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
s = input.next(); // getting a String value
System.out.println("Please enter your age : ");
i = input.nextInt(); // getting an integer
System.out.println("Please enter your salary : ");
d = input.nextDouble(); // getting a double
看看这有何不同:input.next();、i = input.nextInt();、d = input.nextDouble();
根据字符串,int 和 double 的变化方式相同。不要忘记代码顶部的 import 语句。
【讨论】:
要读取一行或一个字符串,您可以使用BufferedReader 对象与InputStreamReader 对象组合,如下所示:
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
【讨论】:
在这里,程序要求用户输入一个数字。之后,程序打印数字的位数和位数的总和。
import java.util.Scanner;
public class PrintNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
int sum = 0;
System.out.println(
"Please enter a number to show its digits");
num = scan.nextInt();
System.out.println(
"Here are the digits and the sum of the digits");
while (num > 0) {
System.out.println("==>" + num % 10);
sum += num % 10;
num = num / 10;
}
System.out.println("Sum is " + sum);
}
}
【讨论】:
这是使用java.util.Scanner的问题中的程序:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
int input = 0;
System.out.println("The super insano calculator");
System.out.println("enter the corrosponding number:");
Scanner reader3 = new Scanner(System.in);
System.out.println(
"1. Add | 2. Subtract | 3. Divide | 4. Multiply");
input = reader3.nextInt();
int a = 0, b = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
// get user input for a
a = reader.nextInt();
Scanner reader1 = new Scanner(System.in);
System.out.println("Enter the scend number");
// get user input for b
b = reader1.nextInt();
switch (input){
case 1: System.out.println(a + " + " + b + " = " + add(a, b));
break;
case 2: System.out.println(a + " - " + b + " = " + subtract(a, b));
break;
case 3: System.out.println(a + " / " + b + " = " + divide(a, b));
break;
case 4: System.out.println(a + " * " + b + " = " + multiply(a, b));
break;
default: System.out.println("your input is invalid!");
break;
}
}
static int add(int lhs, int rhs) { return lhs + rhs; }
static int subtract(int lhs, int rhs) { return lhs - rhs; }
static int divide(int lhs, int rhs) { return lhs / rhs; }
static int multiply(int lhs, int rhs) { return lhs * rhs; }
}
【讨论】:
Scanner对象;一个就足够了。
Scanner input = new Scanner(System.in);
String inputval = input.next();
【讨论】:
【讨论】:
只有一个额外的细节。如果您不想冒内存/资源泄漏的风险,则应在完成后关闭扫描器流:
myScanner.close();
请注意,java 1.7 及更高版本将此视为编译警告(不要问我是如何知道的 :-)
【讨论】:
import java.util.Scanner;
class Daytwo{
public static void main(String[] args){
System.out.println("HelloWorld");
Scanner reader = new Scanner(System.in);
System.out.println("Enter the number ");
int n = reader.nextInt();
System.out.println("You entered " + n);
}
}
【讨论】:
以下是已接受答案的更完善的版本,可解决两个常见需求:
代码
package inputTest;
import java.util.Scanner;
import java.util.InputMismatchException;
public class InputTest {
public static void main(String args[]) {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter integers. Type 0 to exit.");
boolean done = false;
while (!done) {
System.out.print("Enter an integer: ");
try {
int n = reader.nextInt();
if (n == 0) {
done = true;
}
else {
// do something with the input
System.out.println("\tThe number entered was: " + n);
}
}
catch (InputMismatchException e) {
System.out.println("\tInvalid input type (must be an integer)");
reader.nextLine(); // Clear invalid input from scanner buffer.
}
}
System.out.println("Exiting...");
reader.close();
}
}
示例
Please enter integers. Type 0 to exit.
Enter an integer: 12
The number entered was: 12
Enter an integer: -56
The number entered was: -56
Enter an integer: 4.2
Invalid input type (must be an integer)
Enter an integer: but i hate integers
Invalid input type (must be an integer)
Enter an integer: 3
The number entered was: 3
Enter an integer: 0
Exiting...
请注意,如果没有nextLine(),错误的输入将在无限循环中重复触发相同的异常。您可能希望根据具体情况改用next(),但要知道像this has spaces 这样的输入会产生多个异常。
【讨论】:
在main()旁边添加throws IOException,然后
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();
【讨论】:
在java中获取输入很简单,你要做的就是:
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
s = in.nextLine();
System.out.println("You entered string " + s);
System.out.println("Enter an integer");
a = in.nextInt();
System.out.println("You entered integer " + a);
System.out.println("Enter a float");
b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
【讨论】:
import java.util.Scanner;
public class Myapplication{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int a;
System.out.println("enter:");
a = in.nextInt();
System.out.println("Number is= " + a);
}
}
【讨论】:
您可以使用 BufferedReader 获得这样的用户输入:
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
这就是你应用它们的方式
String name = br.readline();
因此,当用户在控制台中输入他的名字时,“字符串名称”将存储该信息。
如果是要存储的数字,代码如下:
int x = Integer.parseInt(br.readLine());
希望这有帮助!
【讨论】:
可以是这样的……
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int i = reader.nextInt();
for (int j = 0; j < i; j++)
System.out.println("I love java");
}
【讨论】:
这是一个使用System.in.read() 函数的简单代码。这段代码只是写出输入的任何内容。如果您只想输入一次,则可以摆脱 while 循环,如果您愿意,可以将答案存储在字符数组中。
package main;
import java.io.IOException;
public class Root
{
public static void main(String[] args)
{
new Root();
}
public Root()
{
while(true)
{
try
{
for(int y = 0; y < System.in.available(); ++y)
{
System.out.print((char)System.in.read());
}
}
catch(IOException ex)
{
ex.printStackTrace(System.out);
break;
}
}
}
}
【讨论】:
我喜欢以下内容:
public String readLine(String tPromptString) {
byte[] tBuffer = new byte[256];
int tPos = 0;
System.out.print(tPromptString);
while(true) {
byte tNextByte = readByte();
if(tNextByte == 10) {
return new String(tBuffer, 0, tPos);
}
if(tNextByte != 13) {
tBuffer[tPos] = tNextByte;
++tPos;
}
}
}
例如,我会这样做:
String name = this.readLine("What is your name?")
【讨论】:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the best program in the world! ");
while (true) {
System.out.print("Enter a query: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.equals("q")) {
System.out.println("The program is ending now ....");
break;
} else {
System.out.println("The program is running...");
}
}
}
}
【讨论】:
import java.util.Scanner;
public class userinput {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Name : ");
String name = input.next();
System.out.print("Last Name : ");
String lname = input.next();
System.out.print("Age : ");
byte age = input.nextByte();
System.out.println(" " );
System.out.println(" " );
System.out.println("Firt Name: " + name);
System.out.println("Last Name: " + lname);
System.out.println(" Age: " + age);
}
}
【讨论】:
class ex1 {
public static void main(String args[]){
int a, b, c;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
c = a + b;
System.out.println("c = " + c);
}
}
// Output
javac ex1.java
java ex1 10 20
c = 30
【讨论】:
args 的元素的制裁:downvote。
正如其他人发布的那样,可以使用扫描仪进行键盘输入。但在这个高度图形化的时代,制作没有图形用户界面 (GUI) 的计算器毫无意义。
在现代 Java 中,这意味着使用像 Scene Builder 这样的 JavaFX 拖放工具来布置类似于计算器控制台的 GUI。 请注意,使用 Scene Builder 非常简单,并且不需要额外的 Java 技能来处理您可能已经拥有的事件处理程序。
对于用户输入,您应该在 GUI 控制台的顶部有一个宽的 TextField。
这是用户输入他们想要执行功能的数字的地方。 在 TextField 下方,您将有一组功能按钮执行基本(即加/减/乘/除和内存/调用/清除)功能。 布置好 GUI 后,您可以添加将每个按钮功能链接到其 Java 实现的“控制器”引用,例如对项目控制器类中的方法的调用。
This video 有点老了,但仍然显示了 Scene Builder 的易用性。
【讨论】:
Scanner 的正确代码非常适合。
您可以使用Scanner 获取用户输入。您可以使用正确的方法对不同的数据类型使用正确的输入验证,例如next() 用于String 或nextInt() 用于Integer。
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
//reads the input until it reaches the space
System.out.println("Enter a string: ");
String str = scanner.next();
System.out.println("str = " + str);
//reads until the end of line
String aLine = scanner.nextLine();
//reads the integer
System.out.println("Enter an integer num: ");
int num = scanner.nextInt();
System.out.println("num = " + num);
//reads the double value
System.out.println("Enter a double: ");
double aDouble = scanner.nextDouble();
System.out.println("double = " + aDouble);
//reads the float value, long value, boolean value, byte and short
double aFloat = scanner.nextFloat();
long aLong = scanner.nextLong();
boolean aBoolean = scanner.nextBoolean();
byte aByte = scanner.nextByte();
short aShort = scanner.nextShort();
scanner.close();
【讨论】:
获取用户输入的最简单方法是使用扫描仪。这是一个应该如何使用它的示例:
import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();
代码行import java.util.Scanner; 告诉程序程序员将在他们的代码中使用用户输入。就像它说的那样,它导入了扫描仪实用程序。 Scanner sc=new Scanner(System.in); 告诉程序启动用户输入。完成此操作后,您必须创建一个没有值的字符串或整数,然后将它们放在a=sc.nextInt(); 或a=sc.nextLine(); 行中。这为变量提供了用户输入的值。然后你可以在你的代码中使用它。希望这会有所帮助。
【讨论】:
使用 JOptionPane 即可实现。
Int a =JOptionPane.showInputDialog(null,"Enter number:");
【讨论】: