简体   繁体   English

Java - 在do while中使用逻辑OR

[英]Java - using logical OR in do while

I'm fairly new at this programming, so please do bear with me. 我对这个编程很新,所以请耐心等待我。

In teaching myself I'm attempting to write a Batteleships game; 在教我自己,我正在尝试写一个Batteleships游戏; not OO at the moment, but rather procedural - little steps at a time. 目前不是OO,而是程序性的 - 一次几步。

I have a method to read the coordinates to fire at, these coordinates I want to then validate to make sure that, well, they're valid. 我有一个方法来读取要触发的坐标,我想要验证这些坐标以确保它们是有效的。 There is one method that checks that they are numbers and within the correct range, the other method is 'supposed' to check through what has already been entered. 有一种方法可以检查它们是数字并且在正确的范围内,另一种方法是“假设”检查已输入的内容。

The issue I'm finding is that I'm not breaking out of the do while loop to progress, the while bit is using logical OR on the two aforementioned methods. 我发现的问题是我没有打破do while循环进行,while位在上述两种方法中使用逻辑OR。 In writing these methods, they both do what they're supposed to do, well I'm not entirely sure about the method that checks whether a coordinate has already been fired at. 在编写这些方法时,他们都做了他们应该做的事情,我不完全确定检查坐标是否已被触发的方法。

Some pointers would be really appreciated (on any aspect of it), thanks! 一些指针将非常感激(在它的任何方面),谢谢!

Code: 码:

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

I propose you add OOP a little and create a class for Coords: 我建议你稍微添加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 + ")";
    }
}

So you code will look somethink like this: 所以你的代码会看起来像这样:

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

Also Set is more applicable in this case. 在这种情况下, Set也更适用。 Set contains no duplicate elements and Set.contains() method works faster then List.contains() . Set不包含重复元素, Set.contains()方法比List.contains()更快。 But if you want to use Set you should implement both equals() and hashCode() methods. 但是如果你想使用Set,你应该实现equals()hashCode()方法。

You want to loop if the coords are invalid or already fired. 如果coords无效或已被触发,您想循环。

So shouldn't the while condition be: 所以不应该是while条件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM