【问题标题】:How do i get rid of my java.lang.NumberFormatException? [duplicate]如何摆脱我的 java.lang.NumberFormatException? [复制]
【发布时间】:2018-11-01 16:08:14
【问题描述】:

我是 Java 新手。我一直在尝试运行一个程序,但它给了我这个错误。我不明白为什么它不起作用。我的输入绝对是一个字符串,该方法返回一个 int。

所以我很困惑为什么会出现格式异常?感谢任何可以提供帮助的人。

public class TestAA3 {

    public static void main(String[] args) { 
        int day = getDay("04/09/2034");
        System.out.print(day);   

    }

    public static String getSubstring( String s, int i, int j) {
        // declaring the String that will eventually be modified and returned by the method
        String Substring = " "; 
        // error message
        if (j<i) {
            throw new IllegalArgumentException("The second integer must be greater than the first");
        } else {
            // defining the limits of the new string
            for ( int position = i;position<=j; position++) {
                // new value of the String
                Substring += " " + s.charAt(position);

            }
            return Substring;
        }
    }

    // calling getSubstring and defining the position inside the string of the int that will be returned
    public static int getDay(String s) {

        if (s.charAt(0)==0){
            String dayString = getSubstring(s,1,1);
            return Integer.valueOf(dayString);
        } else {
            String dayString = getSubstring(s,0,1);
            return Integer.valueOf(dayString);  
        }
    }
}

【问题讨论】:

  • java.lang.NumberFormatException: For input string: " 0 4" " " 不是空字符串,而是包含空格的字符串。请改用""
  • 你不必实现getSubString,Java 已经有这个:s.subString()。你甚至做错了。然后,仔细检查你给 subString 的数字,它们也是错误的。使用Javadoc 作为参考。
  • 你可能想要Character.getNumericValue(s.charAt(0)) == 0而不是s.charAt(0)==0
  • @OHGODSPIDERS 你是对的!!!谢谢!!!

标签: java exception numberformatexception


【解决方案1】:

Substring += " " + s.charAt(position); 应初始化为""。您初始化空格并在方法之前添加两个空格。 getSubstring(s,1,1);其实就是第二个字符。也就是空格再转数字就会报错。

【讨论】:

  • edit您的答案包含仅在英语中找到的单词。
  • 您需要edit 回答,而不是添加英文版本作为评论(这次我已经为您完成了,但您可能需要修复它)。顺便说一句,欢迎来到 Stack Overflow - 请多留些时间并贡献更多内容(英文!)
【解决方案2】:

乍一看,我可以看到 s.charAt(int index) 返回一个 char,所以您实际需要检查的是:s.charAt(0).equals('0'),第二,有更好的方法来处理日期,例如使用数据类型 Date,它允许您调用返回日/月/年的函数。希望有帮助。

【讨论】:

  • 是的!谢谢你的帮助!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 2015-06-22
  • 2021-10-27
  • 1970-01-01
相关资源
最近更新 更多