【问题标题】:Converting a string input from user to a numeric (int) value.将用户输入的字符串转换为数字 (int) 值。
【发布时间】:2011-07-28 20:59:20
【问题描述】:

我一直在尝试将用户字符串输入转换为 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();
 }

【问题讨论】:

  • 您的意见是什么?什么是异常堆栈跟踪?
  • 请发布堆栈跟踪--
  • 只是一个建议,您可以使用String s = addNewUser.substring(0,1) 将第一个字符作为字符串获取。

标签: java string int


【解决方案1】:

您似乎正在尝试将字符串(应该是单个字符,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.");
}

【讨论】:

    【解决方案2】:

    我认为您的意思是让他们输入 0 表示是,输入 1 表示否?也许?

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

    EDIT -- 正如其他人指出的那样,如果你想继续使用 Y 或 N,你应该按照

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

    【讨论】:

    • 好吧,我试图让它对用户来说更直观,而且我故意采取艰难的方式来学习如何在未来处理这种情况。
    【解决方案3】:

    parseInt 仅用于将文本数字转换为整数:其他所有内容都会引发 NumberFormatException。

    如果您想要一个字符的十进制 ASCII 值,只需将其转换为 int。

    【讨论】:

    • 谢谢,我现在知道区别了。
    【解决方案4】:

    请改用if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) {。 或者(正如马克指出的那样)if (addNewUser.toLowerCase().startsWith("y")) {。 顺便说一句,也许看看Apache Commons CLI

    【讨论】:

    • if (addNewUser.toLowerCase().startsWith("y")) { 有点干净。
    • 非常感谢你们,我发现这个答案很完美!我现在将调查“.toLowerCase().startsWith”,因为我还不知道它们。
    【解决方案5】:

    您不能将String 转换为int,除非您知道String 包含一个有效整数。

    首先,使用Scanner 类进行输入更好,因为它更快 如果您是 初学者。这就是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 中是一个非常糟糕的主意 块和catch Exception 在最后。 IOException 可以是 由readline() 函数抛出,parseInt() 可能抛出一个 NumberFormatException,所以你将无法处理 2 分别例外。在这个问题中,代码足够小 这个可以忽略,但是在实践中,会有很多功能 这可能会引发异常,因此很容易忘记究竟是哪个函数引发了哪些异常,并且正确的异常处理变得非常困难。

    【讨论】:

    • 感谢您的回答,我是初学者,从您的回答中学习。感谢您的帮助!
    猜你喜欢
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多