为什么while循环永远不会结束?

时间:2020-02-16 17:15:14

标签: java while-loop do-while

我试图询问扫描仪输入,直到获得有效答案,但我的while循环没有结束。首先,我要求用户输入,然后输入是否有效,则打印出坐标,如果无效,则抛出错误并再次要求输入。 这是我的代码:

{"name" : 10 }

我该如何解决?我也尝试了do while循环,但循环仍未终止:

public static String[] positionQuery(int dim, Scanner test_in) {
        String[] coordinates;
        Scanner stdin = new Scanner(System.in);
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        String s1 = stdin.nextLine();
        coordinates = s1.split(" ");
        String origin = coordinates[0];
        String dest = coordinates[1];

        while (!validCoordinate(origin,dim) || !validCoordinate(dest,dim) || coordinates.length != 2) {
            System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
            Scanner stdin2 = new Scanner(System.in);
            System.out.println("Provide origin and destination coordinates.");
            System.out.println("Enter two positions between A1-H8:");
            String s2 = stdin.nextLine();
            coordinates = s1.split(" ");
            String origin2 = coordinates[0];
            String dest2 = coordinates[1];
        }
        return coordinates;

    }

这是最终代码,但仍未结束:/

public static boolean validCoordinate(String coordinate, int dimension) {
    String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    int [] numbers = new int [dimension];
    int one = 1;
    for(int i = 0; i < dimension; i++){
        numbers[i] = one + i;
    }
    String[] validC = new String [dimension]; //if the first char  is a letter + a number that is determined my the dimension (string concat
    for(int i = 0; i < dimension; i++) {
        for(int j = 0; j < dimension; j++){
            validC [i] = alphabet[j] + Integer.toString(numbers[j]);
        }
    }

    for(int i = 0; i < dimension; i ++) {
        if(validC[i].equals(coordinate)) {
            return true;
        }
        else {
            return false;
        }
    }
        return true;
}

0 个答案:

没有答案