Using substrings to get integers and a character from a string in Java?

Viewed 164

The user is asked to enter a temperature, then the user enters a number followed by either C or F for Celsius or Fahrenheit. The program is then to recognise the temp and what unit the temp is being measured in - using this data it tells your whether the "water" is solid, liquid or gaseous.

I've tried the below

public static void main(String[] args) {
    Scanner myScan = new Scanner(System.in);

    System.out.print("Enter THE temp: ");
    String ent = myScan.next();


    int temp = Integer.parseInt(ent.substring(0,4));

    //char type = ent.charAt();
    //System.out.println(temp);
    // System.out.println(type);

    if (temp >= 100) {
        System.out.println("The water is gaseous");
    } else if (temp < 0) {
        System.out.println("The water is solid");
    } else {
        System.out.println("the water is liquid");
    }

}

When I put the (0,4) in the temp substring, I would've thought that the output would be the first 3 numbers that are entered. Instead I get an error "java.lang.StringIndexOutOfBoundsException" when I enter 1 int or 3.

4 Answers

It looks like it is searching for a character that is out of bounds of the string. Instead of hard coding the string length to 4 use ent.length().

int temp = Integer.parseInt(ent.substring(0,ent.length()-1));

You may also need a formula to convert to Celsius if the last character is F

substring(ent.length()-1).equalsIgnoreCase("F");

First, ask for Celsius or Fahrenheit and then ask for units to the user. http://prntscr.com/phx15j

asking to enter temperature like this--> 50C is wrong.

If you consider the substring function, it takes all characters from beginIndex to endIndex - 1, so here, if you enter "123something", the result will be "123s", as char of index 3 is 's'.

On the other hand, if you only enter "12c", the substring will throw an error, as there is no char at index 3.

Personally, I would've gone for a regex here, as the temperature may be in 1, 2 or 5 chars, depending on how you write it.

s.substring(begin, end) will return a string with characters from begin to end - 1.

If you want to extract all but last character, you can use

s.substring(0, s.length() - 1)

and for only the last character you can use

s.substring(s.length() - 1, s.length()).

You are getting java.lang.StringIndexOutOfBoundsException since the length of entered string is lesser than end (1 < 4 and 3 < 4 in you case).

Related