Search code examples
javajoptionpane

Is it possible to shorten this code?


I'm not exactly a beginner in Java, but I'm also not an expert. Is there any way to shorten this code so that it takes up less space and possibly fewer lines?

JOptionPane.showMessageDialog(null, "The student's names are: " 
  + roster[0][0] + " " + roster[1][0] + ", " 
  + roster[0][1] + " " + roster[1][1] + ", " 
  + roster[0][2] + " " + roster[1][2] + ", and " 
  + roster[0][3] + " " + roster[1][3] + ".");

Solution

  • String rosterString = "";
    for(int i = 0; i < roster[0].length; i++) {
        rosterString += roster[0][i] + " " + roster[1][i] + ", ";
    }
    

    That code will create a string with the names and commas. You could then add in if statements to check if it is near the end to change the , to an and or .