while循环正在改变预期值,原因不明

时间:2014-04-07 11:43:16

标签: java arrays while-loop

我是编码的新手,正在为数组创建一个条件,但是由于某种原因我设置的while循环条件会在不应该的时候更改数组。如果这是显而易见的事情,我很抱歉,但我似乎无法在这里找到适用于我的问题的问题。

代码:

import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
    private static Scanner Keyboard = new Scanner(System.in);

    public static void main(String[] args) {
    //----------------------------------------------------------------
        char group, rLetter;

        int num     = 10; // for test
        int rows    = 10;
        int columns =  8;

        // creating 2d array


        System.out.print("Please enter number of rows               : ");
        rows = Keyboard.nextInt();

        while (rows < 0 || rows >= 10) {
            System.out.print("ERROR:Out of range, try again              : ");
            rows = Keyboard.nextInt();
        }

        double[][] figures = new double[rows + 1][num];

        for(int t = 0; t < rows; t++) {
            rLetter = (char)((t)+(int)'A');
            System.out.print("Please enter number of positions in row " + rLetter + " : ");
            columns = Keyboard.nextInt();

            while(columns < 0 || columns >= 8) {
                System.out.print("ERROR:Out of range, try again              : ");
                columns = Keyboard.nextInt();
            }

            for(int j = 0; j <= columns; j++) {
                figures[j] = new double[j] ;
            }

        }

        // filling the array
        for(int row = 0; row < figures.length; ++row) {
            for(int col = 0; col < figures[row].length; ++col) {
                figures[row][col] = 0.0;
            }
        }

        // printing the array
        for(int row = 0; row < figures.length; ++row) {    
            // printing data row
            group = (char)((row)+(int)'A');
            System.out.print(group + " : ");

            for(int col = 0; col < figures[row].length; ++col) {    
                System.out.print(figures[row][col] + " ");
                System.out.print(" ");
            }

            System.out.println();
        }

        // printing final border
        for(int col = 0; col < figures[0].length; ++col) {
            System.out.print("-+");
        }

        System.out.println("  ");
    }
}

在while循环保持的条件下,第一次输入值时,它会正确显示,但是一旦输入while循环并且值被更正,代码将返回不同的错误或显示错误的数量。 / p>

我不确定为什么会导致结果发生变化,因为如果初始输入超出预期范围,则while循环用于强制输入新值。

1 个答案:

答案 0 :(得分:1)

您需要在每个Keyboard.nextLine()之后致电Keyboard.nextInt()

说明:扫描程序调用nextInt()后,它获取第一个值,并将其余字符串保留为\n。然后我们使用nextLine()消耗字符串的其余部分。

相关问题