Home > Net >  Converting a switch case to a while loop to get data from the database
Converting a switch case to a while loop to get data from the database

Time:12-06

This is the code that I am supposed to change from a switch statement to a while loop

switch (gettingcarValue.getNameDestination()) {
    case "01":
    nameDestination= "Location 1";
    break;

    case "02":
    nameDestination= "Location 2";
    break;

    case "03":
    nameDestination= "Location 3";
    break;

    case "04":
    nameDestination= "Location 4";
    break;

    case "05":
    nameDestination= "Location 5";
    break;

    case "06":
    nameDestination= "Location 6";
    break;

    case "07":
    nameDestination= "Location 7";
    break;

    case "08":
    nameDestination= "Location 8";
    break;

    case "09":
    nameDestination= "Location 9";
    break;

    case "10":
    nameDestination= "Location 10";
    break;

    case "11":
    nameDestination= "Location 11";
    break;

    case "12":
    nameDestination= "Location 12";
    break;

    case "13":
    nameDestination= "Location 13";
    break;

    case "14":
    nameDestination= "Location 14";
    break;

    case "15":
    nameDestination= "Location 15";
    break;

    default:
    nameDestination= "Location not found: "   gettingcarValue.getNameDestination();
}

I want to find a way to make this a simple way through a while loop instead of typing locations in code, i want to fetch them from database and directly display them. Basically finding a effecient way to code and display information.

Edit: So basically, i want to get the case="01" from the database and also the "Location 1". Whatever is hard coded, i want to change it to get from the database.

CodePudding user response:

It appears you only need to parse gettingcarValue.getNameDestination() as an int, then concatenate that with "Location " and assign to nameDestination, assuming that int falls between 1 and 15.

A loop is not necessary.

int n = Integer.parseInt(gettingcarValue.getNameDestination());

if (n >= 1 && n <= 15) {
    nameDestination = ...;
}
else {
    ...;
}
  •  Tags:  
  • java
  • Related