Java: How to properly return result using a method

1363 views java
3

I writing a program that will print "Based on the temperature it is likely" season A, B, C, or D by calling a method.

Code :

import java.util.Scanner;
import javax.swing.*;

public class Seasons {

  public static void main(String[] args) {
    int inputTemp;
    String response = JOptionPane.showInputDialog(null,
            "Enter the temperature");
    inputTemp = Integer.parseInt(response);
    String message = "Based on the temperature of " + inputTemp
            + " it is most likely " + determineSeason(inputTemp);
    JOptionPane.showMessageDialog(null, message);

  }

  public static String determineSeason(int inputTemp) {
    String season = null;
    if (inputTemp > 130 || inputTemp < -20) { 
        JOptionPane.showMessageDialog(null,"Invalid");
    }

    else if (inputTemp >= 90) {
        JOptionPane.showMessageDialog(null,"summer"); }

    else if (inputTemp >= 70 && inputTemp < 90) {
        JOptionPane.showMessageDialog(null,"spring"); }
    else { 
        JOptionPane.showMessageDialog(null,"winter"); }

    return season; 
  }
}

The program is returning with a JOptionPane the season from my method, then presents the JOptionPane from main method where I need it to say "Based on the temperature the season is Season A, B, C, or D.

Any advice on what I'm missing would be appreciated!

answered question

You are sowing the JOptionPane in the determineSeason, but not setting any value to season, and just return it, so it will be null.

@KevinO: I'd say post an answer the next time you see a question like this, since you're correct...

2 Answers

5

You don't assign a result to season and you just return null.

Change each conditional inside of your if statement to something along the lines of this.

String season = null;
if (inputTemp > 130 || inputTemp < -20) {
    season = "invalid";
} else if(inputTemp >= 90) {
    season = "summer";
}

posted this
11

determineSeason should be a private method that doesn't deal with UI parts (doesn't interact with Swing components).

private String determineSeason(int inputTemp) {
    if (inputTemp > 130 || inputTemp < -20) { 
        throw new IllegalArgumentException("Invalid");
    }

    if (inputTemp >= 90) {
        return "summer";
    } else if (inputTemp >= 70 && inputTemp < 90) {
        return "spring";
    } else { 
        return "winter";
    }
}

season can't be "Invalid", you aren't going to display "it is most likely Invalid", so it's better to throw an exception from the method, catch it on the caller side and show an error message window.

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories