Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten an if else statement in java?

Note:Keep in mind that im a newbie both at java and stackoverflow and this is my first question.

Okay, so I was making a basic console based game in java and I had a problem. I had a long list of if else statements. How I can shorten them? I have tried looking at Is there anyway to shorten if else statements instead of going in circles but i didn't get the answer I needed. Here's some sample code from my program:

import java.util.Scanner;

public class FishMain {

public static void main(String[] args) {

    FishClass myFish = new FishClass();

    //Makes a scanner for user input/commands
    Scanner userComSc = new Scanner(System.in);

    //scans for what the user types
    String userCom = userComSc.nextLine();

    //checks if the userCommand isn't /end or exit (when it is it will terminate)
    while(!userCom.equals("/end") && !userCom.equals("/exit")) {

         if(userCom.equals("/dive 1")){
            myFish.dive(1); 
        }
        else if(userCom.equals("/dive 2")){
            myFish.dive(2);
        }
        else if(userCom.equals("/dive 3")){
            myFish.dive(3);

        } else if
           //so on till 99...

   }

I have tried something like this:

if(userCom.startsWith("/dive")){
     int howDeep = Integer.parseInt(userCom);
     myFish.dive(howDeep);
}

but it ends up in an error. Here's the error message:

//user types
/dive 6
Exception in thread "main" java.lang.NumberFormatException: For input string: "/dive 6"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at FishMaster.main(FishMaster.java:40)

Please help me figure out what I am doing wrong.

Edit 1 : Sorry for the confusion of the "/dive 1" (ft) making myFish dive 3ft, that was a typo it is now fixed...

like image 537
ThePhantomGamer Avatar asked Mar 25 '26 19:03

ThePhantomGamer


1 Answers

That was a good idea, unfortunately, you are trying to parse a string with non-numeric characters as an int. You need to substring the Int from the string like so:

if(userCom.startsWith("/dive")){
   String str = userCom.subString(6);
   int howDeep = Integer.parseInt(str);
   myFish.dive(howDeep);
}
like image 91
ltalhouarne Avatar answered Mar 27 '26 10:03

ltalhouarne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!