2014-10-18 12 views
0

這裏是我的代碼:相同的掃描器對象可以採用不同數據類型的輸入嗎?

package Random; 

import java.util.Scanner; 

public class SwitchMonth { 
public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    System.out.println("Enter Year: "); 
    int year = in.nextInt(); 

    System.out.println("Enter month: "); 
    String month = in.nextLine(); 

    //String month = "" 
    switch (month) { 
    case "january": 
    case "march": 
    case "may": 
    case "july": 
    case "august": 
    case "october": 
    case "december": 
     System.out.println("No. of days: 31"); 
     break; 
    case "april": 
    case "june": 
    case "september": 
    case "november": 
     System.out.println("No. of days: 30"); 
     break; 
    case "february": 
     if ((year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0)) 
      System.out.println("No. of days: 29"); 

     else 
      System.out.println("No. of days: 28"); 
     break; 
     default: 
      System.out.println("Wrong month entered."); 
      break; 
    } 
    in.close();  
    } 
} 

輸出:

Enter year: 2000 
Enter month: 
Wrong month entered. 

程序終止,而不採取月份輸入。 如果我硬編碼的月份名稱,那麼它工作正常,但是當我從控制檯輸入它終止與上述輸出。我相信問題在於Scanner對象。 如果我使用另一個月份掃描儀對象,那麼它工作正常。

所以我的問題是:我可以使用相同的掃描儀對象進行int輸入,然後輸入字符串? 如果不是那麼爲什麼?

所有的答案讚賞。提前致謝。

回答

1

nextInt()不消耗ENTER進入今年後,所以nextLine()消耗它,你留下一個空字符串。解決此問題的方法是始終使用nextLine()

int year = Integer.valueOf(in.nextLine()); 

或者,你可以只使用另一nextLine()消耗int後:

int year = in.nextInt(); 
in.nextLine(); // To get rid of the additional \n 
+0

非常感謝!這解決了這個問題。所以基本上nextLine()會在按下回車鍵之前輸入所輸入的值。 – Elysium 2014-10-18 15:07:18

相關問題