2013-02-25 34 views
0

我有一個while循環始終爲真,要求用戶輸入一個字母。當輸入一個字母時,它將在switch語句中查找,然後從switch語句中執行一個代碼塊,在該語句中要求輸入更多的輸入。似乎代碼的輸出在代碼的某些部分被註冊爲用戶的輸入。這裏是我的代碼的簡短範例:用的System.out.println奇怪的問題()和掃描儀

while (true) { 
    System.out.print("Enter a letter :: "); 
    selection = keyboard.nextLine(); 
    selection = selection.toUpperCase(); 

    switch (selection) { 
    case "A": 
     A = null; 
     A = new Matrix(); 
     System.out.println("Default matrix A initialized."); 
     break; 

    case "C": 
     System.out.print("Enter the number of rows (rows > 0) :: "); 
     rows = keyboard.nextInt(); 
     System.out 
       .print("Enter the number of columns (colums > 0) :: "); 
     cols = keyboard.nextInt(); 
     System.out 
       .print("Enter the initial value for each element :: "); 
     initialValue = keyboard.nextInt(); 

     C = null; 
     C = new Matrix(rows, cols, initialValue); 
     System.out.println("Matrix C initialized."); 
     break; 
    } 
} 
+0

您能否更清楚您的問題?乍看之下,似乎是因爲您使用System.out.print()而不是System.out.println() – 2013-02-25 03:59:00

+0

您的預期和實際輸出是什麼? – Jayamohan 2013-02-25 04:02:46

+0

你的代碼給我一個錯誤:無法打開一個String類型的值。只允許使用可轉換的int值或枚舉常量,您應該使用字符('A','B','C')而不是(「A」,「B」,「C」) – 2013-02-25 04:04:34

回答

0

nextInt()獲取下一個INT,但不會讀取新行字符。在您的來源中,如果使用「C」,則使用nextInt(),則需要包含另一個nextLine()以移至下一行。

case "C": 
... 
... 
keyboard.nextLine(); 
break; 
+0

謝謝,我在每個keyboard.nextInt()之後添加了keyboard.nextLine(),現在我的程序正常運行! – Jimmy 2013-02-25 05:13:36