【发布时间】:2013-11-29 19:51:23
【问题描述】:
首先,这是我想出的代码:
package decision;
import java.util.Scanner;
public class ZIP {
public static void main(String[] args) {
Scanner input=new Scanner (System.in);
char zipCode;
System.out.println("Enter your zip code number: ");
zipCode=input.next().charAt(0);
switch (zipCode) {
case 0: case 2: case 3:
System.out.println(zipCode + " is on the East Coast.");
break;
case 4: case 5: case 6:
System.out.println(zipCode + " is in the Central Plains Area.");
break;
case 7:
System.out.println(zipCode + " is in the South.");
break;
case 8: case 9:
System.out.println(zipCode + " is in the West.");
break;
default:
System.out.println(zipCode + " is an invalid ZIP Code.");
}
}
}
(今天刚了解了 switch 结构,想知道当我的代码中充满了嵌套 if 的时候它们在哪里。)
基本上,这个程序应该只接受用户输入的邮政编码的第一个数字(他输入完整的 - 五位数字),但我希望控制台在输出期间打印邮政编码的所有五位数字。
例如,用户会输入87878。该程序将只接受第一个数字(即 8)以将其与特定区域相关联,但是当我将其打印出来时,我希望控制台打印:“(zipCode) is in the West.”
我尝试将 zipCode 的数据类型更改为 char,这样我就可以使用我最近才学到的 charAt(0) 方法,但是鉴于我提供的代码,控制台会打印出来:
Enter your zip code number:
20098
2 is an invalid ZIP Code.
我可以做些什么来获得我想要的输出?提前致谢!
编辑: 这就是我希望控制台的样子:
Enter your zip code number:
20098
20098 is on the East Coast.
【问题讨论】:
标签: java char switch-statement zipcode