How to break this while(true) loop?

后端 未结 2 1508
温柔的废话
温柔的废话 2021-01-27 03:00

Hi I am trying to break from this loop and return the coordinates when both if statements are true. However the loop is never ending. How can I fix it?

public          


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-27 03:17

    See if this works. I just made a Boolean flag variable to get out the while loop. It should make the flag false once it reaches the second if.

    public static String[] positionQuery(int dim, Scanner test_in) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Provide origin and destination coordinates.");
            System.out.println("Enter two positions between A1-H8:");
            Boolean flag = true;
            while(flag) {
                String line = scanner.nextLine();
                String[] coordinates = line.split(" ");
                if(coordinates.length == 2) {
                    String origin = coordinates[0];
                    String dest = coordinates[1];
                    if(validCoordinate(origin, dim) && validCoordinate(dest,dim)) {
                        flag = false;
                        return coordinates;
                    }
                }
                System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
            }
        }
    

提交回复
热议问题