gpt4 book ai didi

java 项目 - 区域

转载 作者:行者123 更新时间:2023-12-02 03:17:52 26 4
gpt4 key购买 nike

我正在开发一个项目,您在扫描仪中输入州的缩写,然后程序会告诉您该州位于美国的哪个地区。我认为我的大部分代码都是正确的,但我有以前从未使用过 switch。

我已经将我的工作改进为一个错误,即我的第一个代码块(switch 部分)中缺少 return 语句。我不知道是否有任何其他代码影响它,所以我只是将其中的大部分内容发布在这里。提前致谢。

import java.util.Scanner;
public class Regions {
public static String getRegion (String stateName){
String region = "";
switch(stateName){
case "ME":
case "VT":
case "NH":
case "MA":
case "CT":
case "RI":
region = "New England";
break;
case "NY":
case "NJ":
case "DE":
case "MD":
case "VA":
case "NC":
case "SC":
region = "Atlantic";
break;
case "GA":
case "FL":
case "MS":
case "AL":
case "LA":
case "TN":
region = "Southeast";
break;
case "PA":
case "OH":
case "MI":
case "IN":
case "IL":
case "WI":
case "MN":
case "KY":
case "WV":
case "IA":
region = "Midwest";
break;
case "ND":
case "SD":
case "KS":
case "NE":
case "MO":
region = "Great Plains";
break;

}
}

public static void main (String[]args){
Scanner s = new Scanner(System.in);
System.out.println("Enter a two-letter state abbreviation:");
String stateName = s.nextLine();
String region = getRegion(stateName);
System.out.print("The state " + stateName);
if (region == "New England"){
System.out.print(" is in the New England region!");
}
else if (region == "Atlantic") {
System.out.print(" is in the Atlantic region!");
}
else if (region == "Southeast") {
System.out.print(" is in the Southeast region!");
}
else if (region == "Midwest") {
System.out.print(" is in the Midwest region!");
}
else if (region == "Great Plains") {
System.out.print(" is in the Great Plains region!");
}
else {
System.out.println ("That's not a state.");
}
}

}`

最佳答案

第一个问题:getRegion()
中缺少返回值只需添加

return region;

添加该方法的末尾。

第二个问题:用==而不是equals比较字符串
在您的 main 中替换所有

if (region == "..."){

if (region.equals("...")){

关于java 项目 - 区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40044046/

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