【问题标题】:Have an issue with Integer.parseInt(string)Integer.parseInt(string) 有问题
【发布时间】:2021-12-26 01:50:50
【问题描述】:
Scanner input = new Scanner (System.in);
        String str = input.nextLine();  // reads x , y
        int x = Integer.parseInt(str.substring(0, str.indexOf(",")));   // this reads the numbers until comma
                                                                                                                                    
        System.out.println(x);
        

当我这样做时,我没有收到错误

22, 23

但是当我这样做时

22 ,23

我收到以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "22 "
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at scratchFiles.stringArray.main(stringArray.java:9)

【问题讨论】:

  • 因为你在, 处拆分,22 不是一个可解析的数字,因为尾随空格,而 22 是可解析的
  • 感谢您的回复,我想了这么多,我的问题应该是我应该怎么做才能在输入的数字末尾结束拆分
  • 看起来那里甚至还有一个换行符,因为错误消息中有一个换行符。
  • 您可以使用trim() 去掉前导和尾随空格
  • 谢谢,我今天学到了一个新功能@QBrute

标签: java string integer parseint


【解决方案1】:

使用trim() 返回字符串的副本,删除前导和尾随空格,以便可以将其解析为Int

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    String str = input.nextLine();  // reads x , y
    int x = Integer.parseInt(str.substring(0, str.indexOf(",")).trim());
    System.out.println(x);
}

【讨论】:

    【解决方案2】:

    问题是当您尝试获取第一个数字时,从 "22 , 23" 的子字符串返回的字符串是 "22[whitespace]"。 使用 Integer.parseInt() 只能将整数字符串作为参数传递,否则会报错。

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        String str = input.nextLine();  // reads x , y
        // get string till , and remove any trailing whitespaces
        String numString = str.substring(0, str.indexOf(",")).trim();
        int x = Integer.parseInt(numString);
        System.out.println(x);
    }
    

    如果字符串是这样的“22 3, 34”,你应该注意的事情很少,你仍然会得到一个异常。所以要小心先清理你的字符串,然后将它传递给 Integer.parseInt()

    【讨论】:

    • 那么你所说的消毒是什么意思,就像如果事情写得不对,就会返回警告?
    • @BDR 通过清理我的意思是你应该确保字符串应该只包含你要在 Integer.parseInt() 函数中传递的数字
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    相关资源
    最近更新 更多