Java 如何在同一用户输入中接受字符串或整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23028789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to accept strings or integers in the same user input
提问by user2399525
I want to accept user input as either an integer or a string in Java but I always get an error no matter what I do.
我想接受用户输入作为 Java 中的整数或字符串,但无论我做什么,我总是收到错误消息。
My code is very simple (I'm a beginner):
我的代码很简单(我是初学者):
System.out.println(
"Enter the row number (or enter e to quit the application):"
);
Scanner rowInput = new Scanner(System.in);
int row1 = rowInput.nextInt();
I want the user also to be able to press "e" to exit.
我希望用户也能够按“e”退出。
I have tried several things:
我尝试了几件事:
1) To convert row1 to a String and and say:
1) 将 row1 转换为 String 并说:
if((String)(row1).equals("e"){
System.out.println("You have quit") }
2) To convert "e" to an integer and say:
2) 将“e”转换为整数并说:
if(row1 == Integer.ParseInt("e"){
System.out.println("You have quit") }
3) To do the switch statement but it said I had incompatible types (String
and an int
).
3)执行switch语句,但它说我有不兼容的类型(String
和一个int
)。
My errors usually say: Exception in thread "main" java.util.InputMismatchException
我的错误通常说: Exception in thread "main" java.util.InputMismatchException
Is there somebody who could help me?
有人可以帮助我吗?
Many thanks in advance!
提前谢谢了!
回答by mok
1) you should say Integer.parseInt()
instead of Integer.ParseInt()
1)你应该说Integer.parseInt()
而不是Integer.ParseInt()
2) if you pass "e" to Integer.parseInt()
you'll get java.lang.NumberFormatException
2)如果你将“e”传递给Integer.parseInt()
你,你会得到 java.lang.NumberFormatException
3) get your input as a string
this way (cause it's safer)*:
3)以string
这种方式获取您的输入(因为它更安全)*:
Scanner rowInput = new Scanner(System.in);
String row = rowInput.next();
if (row.equals("e")) {
//do whatever
}
else if(row.matches("\d+$")) {
//do whatever
}
*In your approach if user enters a non-integer input you'll encounter java.util.InputMismatchException
*在您的方法中,如果用户输入非整数输入,您会遇到 java.util.InputMismatchException
回答by sakura
You can try something like this
你可以试试这样的
Scanner rowInput = new Scanner(System.in);
String inputStr = rowInput.nextLine();
try{
int row1 = Integer.parseInt(inputStr);
} catch (NumberFormatException e) //If exception occurred it means user has entered 'e'
{
if ("e".equals(inputStr)){
System.out.println("quiting application");
}
}
you should read the input from your scanner as String
type and the try to convert that String
input into integer using Integer.parseInt()
.
您应该将扫描仪的输入作为String
类型读取,并尝试String
使用Integer.parseInt()
.
If its successful in parsing, it means user has input an Integer.
And If it fails, it will throw an exception NumberFormatException
which will tell you that its not an Integer. So you can go ahead and check it for e
if it is, do whatever you want as per your requirement.
如果解析成功,说明用户输入了一个整数。如果失败,它会抛出一个异常NumberFormatException
,告诉你它不是一个整数。所以你可以继续检查它e
是否是,根据你的要求做任何你想做的事情。
回答by Rajshekhar Budharam
You can't convert a string into integer, use char ASCII codes instead.
您不能将字符串转换为整数,请改用 char ASCII 代码。
回答by Tomas Pastircak
You can't use nextInt()
if you aren't sure that you will have a number coming in. Also, you can't parse e
as an integer, because it is not an integer, it's either char or string (I'll suggest string in this case).
nextInt()
如果您不确定是否会输入一个数字,则不能使用。此外,您不能解析e
为整数,因为它不是整数,它是字符或字符串(我建议将字符串输入这个案例)。
That means, your code should look like:
这意味着,您的代码应如下所示:
System.out.println("Enter the row number (or enter e to quit the application):");
Scanner rowInput = new Scanner(System.in);
string row1 = rowInput.next();
Then you have the data in a string. You can simply check if the string is e:
然后你有一个字符串中的数据。您可以简单地检查字符串是否为 e:
if (row1.Equals("e")) ...
It is also a good idea to check if the input is actually an integer then. Good way to check it is described here:
检查输入是否实际上是一个整数也是一个好主意。此处描述了检查它的好方法:
回答by Anto Jonie
Try this:
尝试这个:
public class Demo{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String choice = null;
System.out.println("Enter e to exit or some other key to stay:");
choice=s.next();
if(choice.equals("e"))
{
System.out.println("quits");
System.exit(0);
}
else
{
System.out.println("stays");
}
}
}
回答by Stephen C
I have tried several things ....
我已经尝试了几件事......
Attempting to solve this problem by "trying things" is the wrong approach.
试图通过“尝试”来解决这个问题是错误的方法。
The correct approach is to understandwhat is going on, and then modify your solution to take this into account.
正确的方法是了解正在发生的事情,然后修改您的解决方案以将其考虑在内。
The problem you have is that you have a line of input that couldbe either a number or the special value e
which means quit. (And in fact, it could be a couple of other things too ... but I will come to that.)
您遇到的问题是您有一行输入,它可以是数字或e
表示退出的特殊值。(事实上,它也可能是其他一些事情......但我会谈到这一点。)
When you attempt to either:
当您尝试执行以下任一操作时:
call
Scanner.nextInt()
when the next input is not an integer, ORcall
Integer.parseInt(...)
on a String that is not an integer
Scanner.nextInt()
当下一个输入不是整数时调用,或调用
Integer.parseInt(...)
不是整数的字符串
you will get an exception. So what do you do?
你会得到一个例外。所以你会怎么做?
One way is to change what you are doing so that you don't make those calls in those situations. For example:
一种方法是改变你正在做的事情,这样你就不会在这些情况下拨打这些电话。例如:
call
Scanner.hasInt()
to see if the next token is an integer before callingnextInt()
, ortest for the
"e"
case before you attempt to convert the String to an integer.
打电话
Scanner.hasInt()
,看看如果下一个标记是在调用前一个整数nextInt()
,或者"e"
在尝试将 String 转换为整数之前测试案例。
Another way to deal with this is to catchthe exception. For example, you could do something like this:
处理此问题的另一种方法是捕获异常。例如,您可以执行以下操作:
String s = ...
try {
number = Integer.parseInt(s);
} catch (NumberFormatException ex) {
if (s.equals("e")) {
...
}
}
Either way will work, but I'm going to leave you to work out the details.
无论哪种方式都可以,但我要让你去解决细节。
But the real point I'm trying to make is that the right way to solve this is to understand what is happening in your original version / versions, and based on your understanding, modify what you were doing. If you just randomly "try" alternatives that you found with Google, you won't progress to the point of being a productive programmer.
但我想表达的真正观点是,解决这个问题的正确方法是了解您的原始版本/版本中发生了什么,并根据您的理解修改您正在做的事情。如果您只是随意地“尝试”您在 Google 上找到的替代方案,那么您将不会进步到成为一名高效程序员的地步。
I said there were other cases. They are:
我说还有其他情况。他们是:
The user types something that is neither a number of your special
e
character. It could be anything. An empty line,hi mum
...The user types the "end of file" character; e.g.
CTRL-D
on Linux orCTRL-Z
on windows.
用户键入的内容既不是您的特殊
e
字符的数字。它可以是任何东西。一个空行,hi mum
...用户键入“文件结束”字符;例如
CTRL-D
在 Linux 或CTRL-Z
Windows 上。
If you want your program to be robust you need to deal with these cases too.
如果您希望您的程序健壮,您也需要处理这些情况。