首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >战舰坐标输入(带字母) Java

战舰坐标输入(带字母) Java
EN

Stack Overflow用户
提问于 2018-10-20 19:51:27
回答 1查看 1.1K关注 0票数 -1

我是新手(一般是stackoverflow和编程),我正在尝试用Java创建一个战舰游戏。我对我所拥有的非常满意,我知道代码可能不是最有效的,但这不是我想在这里解决的问题。

当输入你的船的位置或者攻击的位置时,在我有它之前,它会询问列是什么,然后分别是行是什么。现在,我正在尝试创建一个方法(称为坐标,这是最后一个),它将允许您一起输入坐标(格式为'A1')。它工作得很好,直到输入错误(有两个字母,两个数字,没有任何东西,等等)。

另一件事是,在坐标方法中,我必须在catch中放入return 20,因为它说缺少return语句,但实际上我不需要返回任何东西,因为这是在do-while循环中。我该怎么做才能让它消失呢?

这是我在这个网站上的第一个问题,所以我不知道是否有人需要这个(我不知道是否有针对不必要代码的规则),但我将把整个程序以及示例输出留在这里。

代码语言:javascript
复制
public static int firing(String[][] board, int hits, int torpedoes, int shipSize, int shipAmount, int whatPlayer)
{
    Scanner userInput = new Scanner(System.in);
    System.out.println("What coordinate do you want?");
    String coordinate = userInput.nextLine();
    int col = coordinates(coordinate, "col");
    int row = coordinates(coordinate, "row");
    while (col > 8 || col < 1 || row > 8 || row < 1)
    {
        System.out.println("That is not a valid coordinate.");
        Scanner input = new Scanner(System.in);
        System.out.println("What coordinate do you want?");
        coordinate = input.nextLine();
        col = coordinates(coordinate, "col");
        row = coordinates(coordinate, "row");
    }

}

public static int letterToNumber(String colLet)
//colLet = column in letter
//This method is to change the column letters to numbers
{
    int num = 1;
    while (!colLet.equalsIgnoreCase("A")&&
           !colLet.equalsIgnoreCase("B")&&
           !colLet.equalsIgnoreCase("C")&&
           !colLet.equalsIgnoreCase("D")&&
           !colLet.equalsIgnoreCase("E")&&
           !colLet.equalsIgnoreCase("F")&&
           !colLet.equalsIgnoreCase("G")&&
           !colLet.equalsIgnoreCase("H"))
    {
        System.out.println("That is not a valid coordinate (not one of the letters)");
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a valid coordinate: "
                + "\nIt should be in the format 'A1' (column then row)");
        String coordinate = input.nextLine();
        colLet = "" + coordinate.charAt(0);
    }
    switch (colLet.toLowerCase())
    {
        case "a": num = 1; break;
        case "b": num = 2; break;
        case "c": num = 3; break;
        case "d": num = 4; break;
        case "e": num = 5; break;
        case "f": num = 6; break;
        case "g": num = 7; break;
        case "h": num = 8; break;
        default: System.out.println("That wasn't a letter!");
    }
    return num;
}


public static int coordinates(String coordinate, String RorC)
// RorC is for Row or column
{
    boolean isValid;
    if (RorC.equals("row"))
    {
        do
        {
            try
            {
                String rowStr = "" + coordinate.charAt(1);
                int row = Integer.parseInt(rowStr);
                isValid = true;
                return row;
            }
            catch(Exception e)
            {
                System.out.println("Error");
                Scanner userInput = new Scanner(System.in);
                System.out.println("That is an invalid coordinate (row probably only had one character)"
                        + "\nPlease enter a valid coordinate."
                        + "\nIt should be in the format 'A1' (column then row)");
                coordinate = userInput.nextLine();
                isValid = false;
                return 20;
            }
        }while(isValid = false);
    }
    else if (RorC.equals("col"))
    {
        do
        {
            try
            {
                String colLet = "" + coordinate.charAt(0);
                int col = letterToNumber(colLet);
                isValid = true;
                return col;
            }
            catch (Exception e)
            {
                System.out.println("Error");
                Scanner userInput = new Scanner(System.in);
                System.out.println(""
                        + "That is an invalid coordinate (col probably had nothing inside it)"
                        + "\nPlease enter a valid coordinate."
                        + "\nIt should be in the format 'A1' (column then row)");
                coordinate = userInput.nextLine();
                isValid = false;
                return 20;
            }
        }while(isValid=false);
    }
    else
    {
        return 0;
    }
}
}

我知道我的代码效率不是很高,但我会在完成后清理它。下面是一个输出示例(我不知道如何将其放入一个没有代码格式的框中)

代码语言:javascript
复制
It is now player 1's turn to choose where to place their ships.
Can the other player please turn around.

You will now be placing ship number 1.
Please write 'H' if you want to create a horizontal ship,
or 'V' if you want it to be vertical.
h
________________________________

   A  B  C  D  E  F  G  H  
1  -  -  -  -  -  -  -  -
2  -  -  -  -  -  -  -  -
3  -  -  -  -  -  -  -  -
4  -  -  -  -  -  -  -  -
5  -  -  -  -  -  -  -  -
6  -  -  -  -  -  -  -  -
7  -  -  -  -  -  -  -  -
8  -  -  -  -  -  -  -  -
________________________________

What coordinates do you want your ship to start on?
If it is horizontal, it will go right from there,
and if it is vertical, it will go down from there.
Please enter the coordinates in the format 'A1' (column then row).
If you enter anything after that, it will be ignored.
u9
That is not a valid coordinate (not one of the letters)
Please enter a valid coordinate: 
It should be in the format 'A1' (column then row)
a1
That is not a valid coordinate (addship).
What coordinates do you want your ship to start on?
Please enter them in the format 'A1' (column then row).
If you enter anything after that, it will be ignored.
d7
________________________________

   A  B  C  D  E  F  G  H  
1  -  -  -  -  -  -  -  -
2  -  -  -  -  -  -  -  -
3  -  -  -  -  -  -  -  -
4  -  -  -  -  -  -  -  -
5  -  -  -  -  -  -  -  -
6  -  -  -  -  -  -  -  -
7  -  -  -  S  S  S  -  -
8  -  -  -  -  -  -  -  -
________________________________

This is your board.

我将感谢任何帮助,即使它是关于不同的东西(不是我正在解决的问题)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-20 21:53:24

我编写了一个小程序,可以输入字符串并将其转换为行和列。它会一直询问用户是否输入了无效的字符串。

示例运行:

代码语言:javascript
复制
Provide a coordinate:
hello?
That is not a valid coordinate! Try again.
X4
That is not a valid coordinate! Try again.
C4
Coordinate{col=3, row=4}

我创建了一个帮助器类来存储坐标。

注意,所有的读/写操作都在一个函数(readCoordinate)中,而所有的字符串操作都在另一个函数(parseCoordinate)中。

如果用户字符串无效,您也可以抛出异常,为了简单起见,我返回了null。

代码语言:javascript
复制
package com.company;

import java.util.Scanner;

class Coordinate {
    private final int col, row;

    public Coordinate(int col, int row) {
        this.col = col;
        this.row = row;
    }

    @Override
    public String toString() {
        return "Coordinate{" +
                "col=" + col +
                ", row=" + row +
                '}';
    }
}


public class Main {
    private final Scanner input;

    public static void main(String[] args) {
        Main m = new Main();
        System.out.println(m.readCoordinate());
    }

    Main() {
        input = new Scanner(System.in);
    }

    private Coordinate readCoordinate() {
        System.out.println("Provide a coordinate:");

        while (true) {
            String line = input.nextLine();
            Coordinate c = parseCoordinate(line);

            if (c != null)
                return c;

            System.out.println("That is not a valid coordinate! Try again.");
        }
    }

    /**
     * Converts a string like A2 into a Coordinate object. Returns null if string is invalid.
     */
    public Coordinate parseCoordinate(String line) {
        line = line.trim().toLowerCase();

        if (line.length() != 2)
            return null;

        char letter = line.charAt(0);

        if (letter > 'h' || letter < 'a')
            return null;
        int col = letter - 'a' + 1;

        char number = line.charAt(1);
        if (number > '8' || number < '1')
            return null;
        int row = number - '1' + 1;

        return new Coordinate(col, row);
    }
}

问题的答案:

什么是@Override?

它是一个可选的装饰器,标志着我正在覆盖一个方法,而不是创建一个新的方法。如果我像tostring一样拼错了toString,我的集成开发环境将会警告我,我实际上并没有覆盖某些东西。你可以忽略它。

为什么col和row是最终的?这不是意味着您不能在以后更改它们吗?

这意味着你不能在第一次赋值后(在构造函数中)赋值给它们。创建不可变的(不可变的==不能被更改)数据类是一种很好的实践。例如,您确信如果您将一个Coordinate传递给一个方法,该方法将不会修改您的实例,并且您不会得到一个混乱的Coordinate

什么是trim?

修剪删除空格(空格,制表符,...)从一根线的两端。" hello world! ".trim()"hello world!"

在main方法之后,扫描器(System.in)的Main()是什么?

我创建了一次扫描仪,并多次使用它。每次要读取字符串时,您都会创建一个新的扫描器。我不认为这对scanner有什么影响,但在某些情况下,你可能会因为重新创建一个对象而丢失一些东西。

在readCoordinate中,while条件反射的真实性是什么?

while (true)的意思是永远循环。有一个return语句打破了原本无限的循环。

在parseCoordinate中,在定义col时,如何将字符添加到整型中?

字符是用数字表示的,所以字符就是引擎盖下的数字。在Java语言中,char就像一个16位的无符号整数,你可以对它们进行普通的整数计算。

为什么readCoordinate类型是private,为什么它是私有的?

不要担心访问修饰符,直到你更好地编程。这在小程序中没有多大意义。您可以标记哪些方法应该从外部调用,哪些方法不应该。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52905350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档