编写一个程序,要求用户输入一年。然后该程序应根据中国十二生肖指示其年份类型。
您将需要:
用于输入的扫描仪对象 输入验证:确保输入的年份为正数! (对此部分使用while循环。) 用于存储输入年份的变量 用于选择适当的星座的开关语句
输出示例如下所示: 输入年份:-89 请输入anno domini(AD)年份! 重新进入年份:1989年 1989年是蛇的一年
当我运行代码并输入一年时,代码会继续运行并重复自身。如何制作它只打印一次?
import java.util.Scanner;
public class ChineseZodiac {
public static void main(String[] args) {
int year;
Scanner in = new Scanner(System.in);
System.out.print("Enter a year: ");
year = in.nextInt();
while (year != 0)
{
switch (year % 12)
{
case 0:
{
System.out.println("The year " + year + " is the year of the Monkey");
break;
}
case 1:
{
System.out.println("The year " + year + " is the year of the Rooster");
break;
}
case 2:
{
System.out.println("The year " + year + " is the year of the Dog");
break;
}
case 3:
{
System.out.println("The year " + year + " is the year of the Pig");
break;
}
case 4:
{
System.out.println("The year " + year + " is the year of the Rat");
break;
}
case 5:
{
System.out.println("The year " + year + " is the year of the Ox");
break;
}
case 6:
{
System.out.println("The year " + year + " is the year of the Tiger");
break;
}
case 7:
{
System.out.println("The year " + year + " is the year of the Rabbit");
break;
}
case 8:
{
System.out.println("The year " + year + " is the year of the Dragon");
break;
}
case 9:
{
System.out.println("The year " + year + " is the year of the Snake");
break;
}
case 10:
{
System.out.println("The year " + year + " is the year of the Horse");
break;
}
case 11:
{
System.out.println("The year " + year + " is the year of the Sheep");
break;
}
}
}
}
}
答案 0 :(得分:0)
while要求年份等于0结束,但问题是你永远不会改变循环内的年份值,所以它会不断重复。
答案 1 :(得分:0)
....代码继续运行并重复自己。我怎么做到这一点 它只打印一次?..
您有while
,它将一直循环到year=0
while (year != 0)
{
应该是
if (year != 0)
{
此外,没有任何意义,因为它永远不会执行case 0
。下面的代码行是没用的。
case 0:
{
System.out.println("The year " + year + " is the year of the Monkey");
break;
}