gpt4 book ai didi

Java:如何使用方法正确返回结果

转载 作者:行者123 更新时间:2023-12-02 01:49:54 26 4
gpt4 key购买 nike

我编写了一个程序,通过调用方法来打印“基于可能的温度”季节 A、B、C 或 D。

代码:

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

该程序从我的方法中返回 JOptionPane 季节,然后从主方法中显示 JOptionPane,我需要它说“根据温度,季节是季节 A、B、C 或 D。

任何关于我所缺少的内容的建议将不胜感激!

最佳答案

defineSeason 应该是一个不处理 UI 部分的私有(private)方法(不与 Swing 组件交互)。

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 不能是“Invalid”,您不会显示“it is most likely Invalid”,所以它是最好从方法中抛出异常,在调用方捕获它并显示错误消息窗口:

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

关于Java:如何使用方法正确返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53135305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com