将用户输入的字符串转换为数字(int)值。

发布于 2024-11-27 03:28:16 字数 793 浏览 0 评论 0原文

我一直在尝试不同的方法将用户字符串输入转换为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

风追烟花雨 2024-12-04 03:28:16

看起来您正在尝试将字符串(应该是单个字符,Y 或 N)转换为其字符值,然后检索该字符的数字表示形式。

如果要将 Y 或 N 转换为十进制表示形式,则必须执行强制转换为 int:

BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.charAt(0);
int integerChar = (int) i;       //The important part
System.out.println(integerChar);

这将返回用户输入的字符的整数表示形式。调用 String.toUpperCase() 方法也可能很有用,以确保 Y/N 或 y/n 的不同输入不会给出不同的值。

但是,您也可以根据字符本身执行 if-else,而不是将其转换为整数。

BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.toUpperCase().charAt(0);
if (i == 'Y') {
    //Handle yes
} else if (i == 'N') {
    //Handle no
} else {
    System.out.println("You've mistyped the answer.");
}

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:

BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.charAt(0);
int integerChar = (int) i;       //The important part
System.out.println(integerChar);

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.

BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.toUpperCase().charAt(0);
if (i == 'Y') {
    //Handle yes
} else if (i == 'N') {
    //Handle no
} else {
    System.out.println("You've mistyped the answer.");
}
七秒鱼° 2024-12-04 03:28:16

我认为您的意思是要求他们输入 0 表示“是”,输入 1 表示“否”?或许?

您要求用户输入 Y 或 N,然后尝试将其解析为整数。那总是会抛出异常。

编辑 - 正如其他人指出的那样,如果您想继续使用 Y 或 N,您应该按照以下方式做一些事情

String addNewUser = answer.readLine();
if ( addNewUser.toLowerCase().startsWith("y") ) {
// Create new profile
}

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

String addNewUser = answer.readLine();
if ( addNewUser.toLowerCase().startsWith("y") ) {
// Create new profile
}
栖竹 2024-12-04 03:28:16

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.

守护在此方 2024-12-04 03:28:16

使用 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?

哀由 2024-12-04 03:28:16

除非您知道 String 包含有效的整数,否则您无法将 String 转换为 int

首先,使用扫描仪< /a> 输入类更好,因为它更快
如果您是,则无需陷入使用流的麻烦
初学者。这就是 Scanner 将用于获取输入的方式:

import java.util.Scanner; // this is where the Scanner class resides

...

Scanner sc = new Scanner(System.in); // "System.in" is the stream, you could also pass a String, or a File object to take input from
System.out.println("Would you like to ... Enter 'Y' or 'N':");
String input = sc.next();
input = input.toUpperCase();
char choice = sc.charAt(0);
if(choice == 'Y') 
{ } // do something

else if(choice == 'N')
{ } // do something

else
System.err.println("Wrong choice!");

此代码也可以缩短为一行(但是您不会
能够检查第三个“错误选择”条件):

if ( new Scanner(System.in).next().toUpperCase().charAt(0) == 'Y')
      { } // do something
   else  // for 'N'
      { } // do something

其次charint 转换只需要显式类型
强制转换:

   char ch = 'A';
   int i = (int)ch;  // explicit type casting, 'i' is now 65 (ascii code of 'A')

第三,即使您从缓冲输入流中获取输入,您
将接受 String 中的输入。因此提取第一个字符
字符串并检查它,只需要调用 charAt()
0 作为参数的函数。它返回一个字符,该字符可以
然后与单引号中的单个字符进行比较,如下所示:

   String s = in.readLine();
   if(s.charAt(0) == 'Y') { } // do something

第四,将整个程序放在 try 中是一个非常糟糕的主意
块并在末尾捕获异常IOException 可以是
readline() 函数抛出,而 parseInt() 可能会抛出
NumberFormatException,因此您将无法处理 2
例外情况分开。在这个问题中,代码足够小
这个可以忽略,但是在实际中,会有很多功能
可能会引发异常,因此很容易丢失确切哪个函数引发了哪些异常,并且正确的异常处理变得相当困难。

You cannot convert String to int, unless you know the String 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:

import java.util.Scanner; // this is where the Scanner class resides

...

Scanner sc = new Scanner(System.in); // "System.in" is the stream, you could also pass a String, or a File object to take input from
System.out.println("Would you like to ... Enter 'Y' or 'N':");
String input = sc.next();
input = input.toUpperCase();
char choice = sc.charAt(0);
if(choice == 'Y') 
{ } // do something

else if(choice == 'N')
{ } // do something

else
System.err.println("Wrong choice!");

This code could also be shortened to one line (however you won't be
able to check a third "wrong choice" condition):

if ( new Scanner(System.in).next().toUpperCase().charAt(0) == 'Y')
      { } // do something
   else  // for 'N'
      { } // do something

Secondly, char to int conversion just requires an explicit type
cast:

   char ch = 'A';
   int i = (int)ch;  // explicit type casting, 'i' is now 65 (ascii code of 'A')

Thirdly, even if you take input from a buffered input stream, you
will take input in a String. So extracting the first character from
the 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:

   String s = in.readLine();
   if(s.charAt(0) == 'Y') { } // do something

Fourthly, its a very bad idea to put the whole program in a try
block and catch Exception at the end. An IOException can be
thrown by the readline() function, and parseInt() could throw a
NumberFormatException, so you won't be able to handle the 2
exceptions 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文