JhasJhas JhasJhas - 9 months ago 42
Java Question

How to return properly in if else and avoid "void" for errors about return

I am having a hard time how to return into specific variable or how to return without getting any error base on my program.

class Facebook {
public static void main(String[]args){

String user = JOptionPane.showInputDialog(null,"Enter Username: ");

String pass = JOptionPane.showInputDialog(null,"Enter Password: ");

JOptionPane.showMessageDialog(null,"Welcome "+ user);
Selection Class = new Selection();

else if (!user.equals("jas")||(!pass.equals("bsit"))) {

"Invalid Username or Password",
"Wrong Authentication",



class Selection{
public Selection1(){

String select = JOptionPane.showInputDialog("[1]Home\n[2]Profile\n[3]Logout");
int numbers = Integer.parseInt(select);

if (numbers == 1){
JOptionPane.showMessageDialog(null,"Mang Tani: Lumakas ang hanging amihan halos nilipad ang mga bubong ng mga bahay\n\nJessica Soho: Isang sikat na pagkain sa davao inubos ng kabataan \n\n Boying Remulla: Walang pasok dahil sa malakas na ulan\n#WalangPasok.");
return select;
else if (numbers == 2){
JOptionPane.showMessageDialog(null,"Name: Ralph Jasper \n\n Age: 17 \n\n Address: Tierra Nevada, General Trias, Cavite");

else if (numbers == 3){


catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please input only numbers","Invalid Input",JOptionPane.ERROR_MESSAGE);

Answer Source

1) you want a method with a return value of a string


public Selection1(){


public String select()

2) all "paths" of a method must result in a return statement. This does not mean a return statement needs to be inside any if else's, but you do need to return something.

Suggestion: declare a String result = ""; outside of the try catch, return it after, outside of the catch, and assign it to your JOptionPane value in between like result = JOptionPane...

3) I'm assuming you actually want that value that's returned?

Selection selector = new Selection();
String selected = selector.select();
// TODO use that value 

Notice: Java naming conventions -- methods are lowerCase, classes are UpperCase.