我如何摆脱我的 java.lang.NumberFormatException?

How do i get rid of my java.lang.NumberFormatException?

我是 java 的新手。我一直在尝试 运行 一个程序,但它给了我这个错误。我不明白为什么它不起作用。我的输入绝对是一个字符串,方法 returns 是一个 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);  
        }
    }
}

乍一看,我看到的是 s.charAt(int index) returns 一个字符,所以您实际需要检查的是:s.charAt(0) .equals('0'),其次,有更好的方法来处理日期,例如使用数据类型 Date,它允许您调用 returns day/month/year 的函数。希望对你有帮助。

Substring += " " + s.charAt(position); 应初始化为 ""。您初始化 space 并在该方法之前添加两个 space。 getSubstring(s,1,1);其实就是第二个字。也就是那个space然后你翻到这个数就会报错