Java - 在do while中使用逻辑OR

时间:2014-05-23 20:01:20

标签: java do-while

我对这个节目很新,所以请耐心等待我。

在自学中我试图写一个Batteleships游戏;目前不是OO,而是程序性的 - 一次只有几步。

我有一个方法来读取要触发的坐标,我想要验证这些坐标以确保它们是有效的。 有一种方法可以检查它们是数字并且在正确的范围内,另一种方法是“假设”检查已输入的内容。

我发现的问题是我没有打破do while循环进行,while位在上述两种方法中使用逻辑OR。在编写这些方法时,他们都做了他们应该做的事情,我不完全确定检查坐标是否已被触发的方法。

非常感谢(在任何方面),谢谢!

代码:

public static String inputCoords(List<String> coordsFired){
    Scanner sc = new Scanner(System.in);

    //Console c = System.console();
    String coordsEntered;

    do {
        System.out.println("in do\\while");
        System.out.println("Enter coordinates as 'x, y': ");
        coordsEntered = sc.nextLine();
        System.out.println("end of do\\while loop");
    } while(!validateCoords(coordsEntered) 
         || !coordsFiredAt(coordsEntered, coordsFired));

    coordsFired.add(coordsEntered);
    System.out.println("contents of List<String> coordsFired" + coordsFired);

    return coordsEntered;
}

public static boolean validateCoords(String coordsEntered){
    boolean results;
    int x, y;
    String strx = splitCoordsString(coordsEntered, 'x');
    String stry = splitCoordsString(coordsEntered, 'y');

    if (numericCheckCoordsFire(strx) && numericCheckCoordsFire(stry)) {
        x = Integer.parseInt(strx);
        y = Integer.parseInt(stry);

        if (x > 25 || y > 25) {
            results = false;
            System.out.println("The dimensions of the board are 25 x 25, 'x,y' entered must be less than this.  You entered '" + strx + "' for x and '" + stry + "' for y.");
        } else {
            results = true;
        }
    } else {
        results = false;
        System.out.println("Coords are supposed to be numbers...  You entered '" + strx + "' for x and '" + stry + "' for y.");
    }

    System.out.println(results);
    return results;
}

public static boolean coordsFiredAt(String coordsEntered, List<String> coordsFired) {
    boolean results = false;

    // go through each item in the list and compare against coordsEntered
    for (String s : coordsFired) {
        System.out.println("in for loop, printing iterated var" + s);

        if (s.equals(coordsEntered)) {
            // put these matched coordsFire into listHit
            results = false;
        } else {
            System.out.println("already fired at " + coordsEntered);
            results = true;
        }
    }

    return results;
}

2 个答案:

答案 0 :(得分:3)

我建议你稍微添加OOP并为Coords创建一个类:

public class Coords {

    private final int x;
    private final int y;

    public Coords(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    /**
     * This method is used for Coords comparison
     */
    @Override
    public boolean equals(Object o) {
        Coords coords = (Coords) o;
        return y == coords.y && coords.x ==x;
    }

    /**
     * This method is used to output coords.
     */
    @Override
    public String toString() {
        return "(" + x + "," + y + ")";
    }
}

所以你的代码看起来会像这样:

public static Coords inputCoords(List<Coords> coordsFired) {
        Scanner sc = new Scanner(System.in);

        //Console c = System.console();
        Coords coords;

        do {
            System.out.println("in do\\while");
            System.out.println("Enter coordinates as 'x, y': ");
            String coordsEntered = sc.nextLine();
            coords = parseCoords(coordsEntered);
            System.out.println("end of do\\while loop");
        } while (coords == null || !areCoordsValid(coords) || !areCoordsNotFired(coords, coordsFired));

        coordsFired.add(coords);
        System.out.println("contents of List<String> coordsFired" + coordsFired);

        return coords;
    }

    public static boolean areCoordsValid(Coords coords) {
        boolean result = true;

        if (coords.getX() > 25 || coords.getY() > 25) { // I think you also need to validate that it is possible values
            result = false;
            System.out.println("The dimensions of the board are 25 x 25, 'x,y' entered must be less than this. " +
                    "You entered '" + coords.getX() + "' for x and '" + coords.getY() + "' for y.");
        }

        return result;
    }

    public static boolean areCoordsNotFired(Coords coords, List<Coords> firedCoards) {
        boolean result = true;
        if (firedCoards.contains(coords)) {
            result = false;
            System.out.println("You already fired at " + coords.getX() + "," + coords.getY());
        }
        return result;
    }

    public static Coords parseCoords(String coordsEntered) {
        Coords coords = null;
        try {
            String[] splittedCoords = coordsEntered.split(","); // Method splits values by comma. It should return an array of Strings with x value at the first element and y at the second one;
            if (splittedCoords.length == 2) {
                String x = splittedCoords[0].trim(); // Method removes all spaces at the beginning and ending of a passed String
                String y = splittedCoords[1].trim();
                coords = new Coords(Integer.parseInt(x), Integer.parseInt(y)); //Creates new instance of Coords class. x and y are passed as constructor params.
            } else {
                System.out.println("Format for coords is wrong.  You entered '" + coordsEntered + "'.");
            }

        } catch (NumberFormatException e) { // Integer.parseInt throws an exception if the string does not contain parsable integer.
            // We catch an exception and handle it by writing a message
            System.out.println("Coords are supposed to be numbers...  You entered '" + coordsEntered + "'.");
        }
        return coords;
    }

在这种情况下,Set更适用。 Set不包含重复元素, Set.contains()方法比 List.contains()更快。但是如果你想使用Set,你应该同时实现 equals() hashCode()方法。

答案 1 :(得分:1)

如果coords无效或已经被解雇,你想循环。

所以不应该是while条件:

while(!validateCoords(coordsEntered) 
     || coordsFiredAt(coordsEntered, coordsFired))