System.out.println()和Scanner的奇怪问题

时间:2013-02-25 03:57:01

标签: java system java-7 println

我有一个始终为true的while循环,要求用户输入一个字母。当输入一个字母时,它在switch语句中查找,然后从switch语句执行一个代码块,其中要求输入更多的输入。看起来代码的输出在代码的某些部分被注册为用户的输入。以下是我的代码的简要示例:

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

1 个答案:

答案 0 :(得分:0)

nextInt()获取下一个int,但不读取新行字符。在您的来源中,您使用nextInt()以防“C”,您需要包含另一个nextLine()以移至下一行。

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