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?
如何使用Java获取用户输入?
24 个解决方案
#1
318
One of the simplest ways is to use a Scanner
object as follows:
最简单的方法之一是使用扫描仪对象如下:
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();
#2
259
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
来自DataInputStream类的readLine方法已被弃用。要获取字符串值,应该使用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.
显然,这种方法在某些ide中效果不佳。
#3
42
You can use the Scanner class or the Console class
您可以使用扫描器类或控制台类
Console console = System.console();
String input = console.readLine("Enter input:");
#4
17
You can get user input using BufferedReader
.
您可以使用BufferedReader获得用户输入。
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.println("Enter your Account number: ");
accStr = br.readLine();
It will store a String
value in accStr
so you have to parse it to an int
using Integer.parseInt
.
它将在accStr中存储一个字符串值,因此您必须使用Integer.parseInt将其解析为int。
int accInt = Integer.parseInt(accStr);
#5
13
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.
#6
13
You can make a simple program to ask for user's name and print what ever the reply use inputs.
您可以制作一个简单的程序来询问用户的名字,并打印任何回复使用的输入。
Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.
或者让用户输入两个数字,你可以加、乘、减或除这些数字,并打印用户输入的答案,就像计算器的行为一样。
So there you need Scanner class. You have to import java.util.Scanner;
and in the code you need to use
这里需要扫描器类。必须导入java.util.Scanner;在你需要使用的代码中
Scanner input = new Scanner(System.in);
Input is a variable name.
输入是一个变量名。
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
See how this differs: input.next();
, i = input.nextInt();
, d = input.nextDouble();
查看该如何不同:input.next();
According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.
根据字符串,int和double的变化方式与其他的相同。不要忘记代码顶部的import语句。
Also see the blog post "Scanner class and getting User Inputs".
还可以查看博客文章“扫描器类和获取用户输入”。
#7
6
To read a line or a string, you can use a BufferedReader
object combined with an InputStreamReader
one as follows:
要读取一行或字符串,可以使用BufferedReader对象结合InputStreamReader对象,如下所示:
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
#8
5
Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.
在这里,程序要求用户输入一个数字。然后,程序打印数字的数字和数字的总和。
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);
}
}
#9
4
Use the System
class to get the input.
使用System类获取输入。
http://fresh2refresh.com/java-tutorial/java-input-output/ :
http://fresh2refresh.com/java-tutorial/java-input-output/:
How data is accepted from keyboard ?
We need three objects,
我们需要三个对象,
- System.in
- 系统
- InputStreamReader
- InputStreamReader
BufferedReader
BufferedReader
- InputStreamReader and BufferedReader are classes in java.io package.
- InputStreamReader和BufferedReader是java中的类。io包。
- The data is received in the form of bytes from the keyboard by System.in which is an InputStream object.
- 数据以字节的形式从键盘接收到系统。其中是一个InputStream对象。
- Then the InputStreamReader reads bytes and decodes them into characters.
- 然后InputStreamReader读取字节并将它们解码为字符。
- 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.
- 最后,BufferedReader对象从字符输入流中读取文本,对字符进行缓冲,以便有效地读取字符、数组和行。
InputStreamReader inp = new InputStreamReader(system.in);
BufferedReader br = new BufferedReader(inp);
#10
4
Here is your program from the question using java.util.Scanner
:
以下是您使用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; }
}
#11
4
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 :-)
注意java 1.7,稍后将其捕获为编译警告(不要问我如何知道:-)
#12
3
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);
}
}
#13
3
Scanner input=new Scanner(System.in); int integer=input.nextInt(); String string=input.next(); long longInteger=input.nextLong();
#14
2
Scanner input = new Scanner(System.in);
String inputval = input.next();
#15
2
Add throws IOException
beside main()
, then
然后在main()旁边添加抛出IOException
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();
#16
2
It is very simple to get input in java, all you have to do is:
用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);
}
}
#17
2
You can get user input like this using a BufferedReader:
你可以使用BufferedReader来获取这样的用户输入:
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
This is how you apply them
这就是应用它们的方法
String name = br.readline();
So when the user types in his name into the console, "String name" will store that information.
因此,当用户在控制台输入他的名字时,“String name”将存储该信息。
If it is a number you want to store, the code will look like this:
如果是你想存储的数字,代码会是这样的:
int x = Integer.parseInt(br.readLine());
Hop this helps!
跳这帮助!
#18
2
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);
}
}
#19
2
Can be something like this...
可以是这样的……
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");
}
#20
1
This is a simple code that uses the System.in.read()
function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.
这是一个使用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;
}
}
}
}
#21
1
I like the following:
我喜欢下面的:
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;
}
}
}
and for example, I would do:
举个例子,我想:
String name = this.readLine("What is your name?")
#22
1
Here is a more developed version of the accepted answer that addresses two common needs:
下面是一个更成熟的答案版本,它解决了两个常见的需求:
- Collecting user input repeatedly until an exit value has been entered
- 重复收集用户输入,直到输入出口值
- Dealing with invalid input values (non-integers in this example)
- 处理无效的输入值(本例中的非整数)
Code
代码
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();
}
}
Example
例子
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...
Note that without nextLine()
, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next()
instead depending on the circumstance, but know that input like this has spaces
will generate multiple exceptions.
注意,没有nextLine(),坏的输入将在无限循环中重复触发相同的异常。您可能想要使用next(),这取决于环境,但是要知道像这样的输入具有空格,将生成多个异常。
#23
-1
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);
}
}
#24
-1
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
#1
318
One of the simplest ways is to use a Scanner
object as follows:
最简单的方法之一是使用扫描仪对象如下:
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();
#2
259
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
来自DataInputStream类的readLine方法已被弃用。要获取字符串值,应该使用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.
显然,这种方法在某些ide中效果不佳。
#3
42
You can use the Scanner class or the Console class
您可以使用扫描器类或控制台类
Console console = System.console();
String input = console.readLine("Enter input:");
#4
17
You can get user input using BufferedReader
.
您可以使用BufferedReader获得用户输入。
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.println("Enter your Account number: ");
accStr = br.readLine();
It will store a String
value in accStr
so you have to parse it to an int
using Integer.parseInt
.
它将在accStr中存储一个字符串值,因此您必须使用Integer.parseInt将其解析为int。
int accInt = Integer.parseInt(accStr);
#5
13
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.
#6
13
You can make a simple program to ask for user's name and print what ever the reply use inputs.
您可以制作一个简单的程序来询问用户的名字,并打印任何回复使用的输入。
Or ask user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like a behavior of a calculator.
或者让用户输入两个数字,你可以加、乘、减或除这些数字,并打印用户输入的答案,就像计算器的行为一样。
So there you need Scanner class. You have to import java.util.Scanner;
and in the code you need to use
这里需要扫描器类。必须导入java.util.Scanner;在你需要使用的代码中
Scanner input = new Scanner(System.in);
Input is a variable name.
输入是一个变量名。
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
See how this differs: input.next();
, i = input.nextInt();
, d = input.nextDouble();
查看该如何不同:input.next();
According to a String, int and a double varies same way for the rest. Don't forget the import statement at the top of your code.
根据字符串,int和double的变化方式与其他的相同。不要忘记代码顶部的import语句。
Also see the blog post "Scanner class and getting User Inputs".
还可以查看博客文章“扫描器类和获取用户输入”。
#7
6
To read a line or a string, you can use a BufferedReader
object combined with an InputStreamReader
one as follows:
要读取一行或字符串,可以使用BufferedReader对象结合InputStreamReader对象,如下所示:
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
#8
5
Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.
在这里,程序要求用户输入一个数字。然后,程序打印数字的数字和数字的总和。
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);
}
}
#9
4
Use the System
class to get the input.
使用System类获取输入。
http://fresh2refresh.com/java-tutorial/java-input-output/ :
http://fresh2refresh.com/java-tutorial/java-input-output/:
How data is accepted from keyboard ?
We need three objects,
我们需要三个对象,
- System.in
- 系统
- InputStreamReader
- InputStreamReader
BufferedReader
BufferedReader
- InputStreamReader and BufferedReader are classes in java.io package.
- InputStreamReader和BufferedReader是java中的类。io包。
- The data is received in the form of bytes from the keyboard by System.in which is an InputStream object.
- 数据以字节的形式从键盘接收到系统。其中是一个InputStream对象。
- Then the InputStreamReader reads bytes and decodes them into characters.
- 然后InputStreamReader读取字节并将它们解码为字符。
- 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.
- 最后,BufferedReader对象从字符输入流中读取文本,对字符进行缓冲,以便有效地读取字符、数组和行。
InputStreamReader inp = new InputStreamReader(system.in);
BufferedReader br = new BufferedReader(inp);
#10
4
Here is your program from the question using java.util.Scanner
:
以下是您使用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; }
}
#11
4
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 :-)
注意java 1.7,稍后将其捕获为编译警告(不要问我如何知道:-)
#12
3
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);
}
}
#13
3
Scanner input=new Scanner(System.in); int integer=input.nextInt(); String string=input.next(); long longInteger=input.nextLong();
#14
2
Scanner input = new Scanner(System.in);
String inputval = input.next();
#15
2
Add throws IOException
beside main()
, then
然后在main()旁边添加抛出IOException
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();
#16
2
It is very simple to get input in java, all you have to do is:
用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);
}
}
#17
2
You can get user input like this using a BufferedReader:
你可以使用BufferedReader来获取这样的用户输入:
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
This is how you apply them
这就是应用它们的方法
String name = br.readline();
So when the user types in his name into the console, "String name" will store that information.
因此,当用户在控制台输入他的名字时,“String name”将存储该信息。
If it is a number you want to store, the code will look like this:
如果是你想存储的数字,代码会是这样的:
int x = Integer.parseInt(br.readLine());
Hop this helps!
跳这帮助!
#18
2
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);
}
}
#19
2
Can be something like this...
可以是这样的……
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");
}
#20
1
This is a simple code that uses the System.in.read()
function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.
这是一个使用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;
}
}
}
}
#21
1
I like the following:
我喜欢下面的:
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;
}
}
}
and for example, I would do:
举个例子,我想:
String name = this.readLine("What is your name?")
#22
1
Here is a more developed version of the accepted answer that addresses two common needs:
下面是一个更成熟的答案版本,它解决了两个常见的需求:
- Collecting user input repeatedly until an exit value has been entered
- 重复收集用户输入,直到输入出口值
- Dealing with invalid input values (non-integers in this example)
- 处理无效的输入值(本例中的非整数)
Code
代码
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();
}
}
Example
例子
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...
Note that without nextLine()
, the bad input will trigger the same exception repeatedly in an infinite loop. You might want to use next()
instead depending on the circumstance, but know that input like this has spaces
will generate multiple exceptions.
注意,没有nextLine(),坏的输入将在无限循环中重复触发相同的异常。您可能想要使用next(),这取决于环境,但是要知道像这样的输入具有空格,将生成多个异常。
#23
-1
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);
}
}
#24
-1
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