将用户输入的字符串转换为数字(int)值。
我一直在尝试不同的方法将用户字符串输入转换为 int 我可以比较并构建“if-then”语句。每次我尝试测试它时,它都会抛出异常。任何人都可以查看我的Java代码并帮助我找到方法吗?我对此一无所知(也是编程新手)。如果我违反了任何规则,请告诉我我是新来的。谢谢。
无论如何,这是代码:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mistyped the answer.");
e.getMessage();
}
I've been trying different methods for converting a user string input into an int I could compare and build an "if-then" statement. Every time I tried testing it, it just threw exception. Can anyone look at my Java code and help me find the way? I'm clueless about it (also a noob in programming). If I'm breaking any rules please let me know I'm new here. Thank you.
Anyway, here is the code:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mistyped the answer.");
e.getMessage();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看起来您正在尝试将字符串(应该是单个字符,Y 或 N)转换为其字符值,然后检索该字符的数字表示形式。
如果要将 Y 或 N 转换为十进制表示形式,则必须执行强制转换为 int:
这将返回用户输入的字符的整数表示形式。调用 String.toUpperCase() 方法也可能很有用,以确保 Y/N 或 y/n 的不同输入不会给出不同的值。
但是,您也可以根据字符本身执行 if-else,而不是将其转换为整数。
It seems like you are trying to convert the string (which should be a single character, Y or N) into its character value, and then retrieve the numerical representation of the character.
If you want to turn Y or N into their decimal representation, you have to perform a cast to int:
This will return the integer representation of the character that the user input. It may also be useful to call the String.toUpperCase() method in order to ensure that different inputs of Y/N or y/n do not give different values.
However, you could also do an if-else based upon the character itself, rather than converting it to an integer.
我认为您的意思是要求他们输入 0 表示“是”,输入 1 表示“否”?或许?
您要求用户输入 Y 或 N,然后尝试将其解析为整数。那总是会抛出异常。
编辑 - 正如其他人指出的那样,如果您想继续使用 Y 或 N,您应该按照以下方式做一些事情
I think you meant to ask them to Enter 0 for yes and 1 for No ? Maybe?
You're asking the user to type Y or N and then you're trying to parse that to an integer. That will always throw an exception.
EDIT -- As others have pointed out, if you want to continue to use Y or N, you should do something along the lines of
parseInt 只是用于将文本数字转换为整数:其他所有内容都会得到 NumberFormatException。
如果你想要一个字符的十进制 ASCII 值,只需将其转换为 int 即可。
parseInt is just for converting text numbers into integers: everything else gets a NumberFormatException.
If you want the decimal ASCII value of a character, just cast it to an int.
使用
if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) {
代替。或者(正如 Mark 所指出的)
if (addNewUser.toLowerCase().startsWith("y")) {
。顺便说一句,也许看看Apache Commons CLI?
Use
if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) {
instead.Or (as Mark pointed)
if (addNewUser.toLowerCase().startsWith("y")) {
.BTW maybe look at Apache Commons CLI?
除非您知道
String
包含有效的整数,否则您无法将String
转换为int
。首先,使用扫描仪< /a> 输入类更好,因为它更快
如果您是,则无需陷入使用流的麻烦
初学者。这就是
Scanner
将用于获取输入的方式:...
此代码也可以缩短为一行(但是您不会
能够检查第三个“错误选择”条件):
其次,
char
到int
转换只需要显式类型强制转换:
第三,即使您从缓冲输入流中获取输入,您
将接受
String
中的输入。因此提取第一个字符字符串并检查它,只需要调用
charAt()
以 0 作为参数的函数。它返回一个字符,该字符可以
然后与单引号中的单个字符进行比较,如下所示:
第四,将整个程序放在
try
中是一个非常糟糕的主意块并在末尾捕获
异常
。IOException
可以是由
readline()
函数抛出,而parseInt()
可能会抛出NumberFormatException
,因此您将无法处理 2例外情况分开。在这个问题中,代码足够小
这个可以忽略,但是在实际中,会有很多功能
可能会引发异常,因此很容易丢失确切哪个函数引发了哪些异常,并且正确的异常处理变得相当困难。
You cannot convert
String
toint
, unless you know theString
contains a valid integer.Firstly, using the Scanner class for input is better, since its faster
and you don't need to get into the hassle of using streams, if you're
a beginner. This is how
Scanner
will be used to take input:...
This code could also be shortened to one line (however you won't be
able to check a third "wrong choice" condition):
Secondly,
char
toint
conversion just requires an explicit typecast:
Thirdly, even if you take input from a buffered input stream, you
will take input in a
String
. So extracting the first character fromthe string and checking it, simply requires a call to the
charAt()
function with 0 as a parameter. It returns a character, which can
then be compared to a single character in single quotes like this:
Fourthly, its a very bad idea to put the whole program in a
try
block and
catch
Exception
at the end. AnIOException
can bethrown by the
readline()
function, andparseInt()
could throw aNumberFormatException
, so you won't be able to handle the 2exceptions separately. In this question, the code is small enough for
this to be ignored, but in practice, there will be many functions
that can throw exceptions, hence it becomes easy to lose track of exactly which function threw what exception and proper exception handling becomes quite difficult.