JavaNewb
JavaNewb

Reputation: 87

Returning 2 different strings

Is it possible to do what this code is trying to do (Current code format causes an error)

public String fileStream(){
    Object[] yesNo = {"Yes",
          "No",};
int nn = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
    if (nn == 0){
        String savedBallNumber = readFromFile();
        return savedBallNumber;
    }
    if (nn == 1){
        String ballNumber = JOptionPane.showInputDialog("Please enter the number of balls you want on the screen:");
        return ballNumber;
    }
}

Error I get when I hover over fileStream is "This method must return a result of type String"

Upvotes: 1

Views: 75

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your problem is your code has returns in two if blocks, but has no else block meaning that thee's a chance that the method will end without returning anything:

For example:

public String someMethod {
  if (a) {
    return "foo";
  }
  if (b) {
    return "bar";
  }
}

What does it return if neither a nor b are true.

Solution: change the last if block to an else block:

public String fileStream() {
  Object[] yesNo = { "Yes", "No"};
  int nn = JOptionPane.showOptionDialog(null,
        "Would you like to use previously entered data?", "Welcome Back?",
        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
        yesNo, yesNo[1]);
  if (nn == 0) {
     String savedBallNumber = readFromFile();
     return savedBallNumber;
  } else {
     String ballNumber = JOptionPane.showInputDialog("Please enter the number of balls you want on the screen:");
     return ballNumber;
  }
}

Upvotes: 4

Related Questions