Search code examples
javaexceptionnumberformatexception

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


I am new to java. I have been trying to run a program but it gives me this error. I don't understand why it doesn't work. My input is definitely a string and the method returns an int.

So I am confused as to why I get a format exception? Thanks to anyone that can help.

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);  
        }
    }
}

Solution

  • Substring += " " + s.charAt(position); should be initialized to "". You initialize the space and add two spaces before the method. getSubstring(s,1,1); In fact, it is the second character. That is, the space and then you will turn to the number and you will get an error.