2017-10-09 116 views
-3

編寫一個程序,要求用戶輸入一年。然後該程序應該指出基於中國十二生肖的年份類型。while循環和開關不斷重複

你將需要:

掃描器對象輸入 輸入驗證:確保今年進入是肯定的! (使用while循環對於這部分) 變量來存儲年進入 switch語句來選擇合適的星座

輸出的樣本如下所示: 輸入年份:-89 進入請anni 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它將退出否則請求並給予掃描儀=新掃描儀(System.in); System.out.print(「Enter a year:」); year = in.nextInt(); –

+1

當然,while循環不斷重複。這就是它的重點。除非將年份變量更改爲0或突破它,否則它將保持循環。 – Ivar

+2

'「我如何製作它只是打印一次?」 - 通過刪除循環。循環的*目的是重複一些事情。 – David

回答

0

的同時需要一年等於0結束,但問題是,你永遠不變的循環內的年份值,所以它只會不斷重複。

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