简体   繁体   中英

Java: How to properly return result using a method

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!

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";
}

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:

class Seasons {

    public static void main(String[] args) {
        String response = JOptionPane.showInputDialog(null, "Enter the temperature");
        int inputTemp = Integer.parseInt(response);
        try {
            String message = String.format("Based on the temperature of %d, it is most likely %s", inputTemp, determineSeason(inputTemp));
            JOptionPane.showMessageDialog(null, message);
        } catch (IllegalTemperatureValueException | NumberFormatException e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

    private static String determineSeason(int inputTemp) throws IllegalTemperatureValueException {
        if (inputTemp > 130 || inputTemp < -20) {
            throw new IllegalTemperatureValueException("incorrect temperature value");
        }

        return inputTemp >= 90 ? "summer" : (inputTemp >= 70 ? "spring" : "winter");
    }
}

class IllegalTemperatureValueException extends Exception {
    public IllegalTemperatureValueException(String message) {
        super(message);
    }
}

I would advise you to use interfaces and java 8 Streams. That way you avoid a lot of ifs, which makes the code less verbose, and the introduction of a new class becomes trivial.

Even in small or simple projects, consider interface-oriented programming, which makes you think more before declaring a new method.

Season.java

public abstract class Season {

    public <T extends Season> Stream season(Integer temperature) {
        if (temperature <= max() && temperature >= min()) {
            return Stream.of(this);
        }
        return Stream.empty();
    }

    public abstract Integer max();

    public abstract Integer min();

    @Override
    public abstract String toString();
}

Summer.java

public class Summer extends Season {

    @Override
    public String toString() {
        return "Summer";
    }

    @Override
    public Integer max() {
        return 90;
    }

    @Override
    public Integer min() {
        return 70;
    }
}

Spring.java

public class Spring extends Season {

    @Override
    public String toString() {
        return "Spring";
    }

    @Override
    public Integer max() {
        return 69;
    }

    @Override
    public Integer min() {
        return 40;
    }
}

Main.java

public class Main {

    public static void main(String[] args) {

        Collection<Season> seasons = new ArrayList();
        seasons.add(new Summer());
        seasons.add(new Winter());
        seasons.add(new Season() {
            @Override
            public Integer max() {
                return 39;
            }

            @Override
            public Integer min() {
                return 10;
            }

            @Override
            public String toString() {
                return "Winter";
            }
        });

        String response = JOptionPane.showInputDialog(null, "Enter the temperature");
        int temperature = Integer.parseInt(response);
        String msg = "Based on the temperature of %d it is most likely %s%n";

        seasons.stream().forEach(s -> {
            s.season(temperature).findAny().ifPresent(t -> {
                String message = String.format(msg, temperature, t);
                JOptionPane.showMessageDialog(null, message);
            });
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM