簡體   English   中英

在ONE函數中獲取2D Array的坐標

[英]Getting coordinates for 2D Array within ONE function

如何在一個函數中從用戶檢索X和Y坐標?(對於需要數組坐標的java游戲)

“getX函數將詢問用戶X坐標。它將返回用戶輸入的數字.getY具有相同的功能,消息被調整為要求Y坐標。”

這是我需要遵循的功能。 需要使用返回值將數字放在2D數組中。 我如何在一個功能中實現這一目標?

board[x][y] = 1;

編輯:我只能在java中做一些事情(對於計算測試,因此使用我們所教過的任何東西都不會獲​​得分數--AQA AS Level)。 我需要在函數中掃描用戶的輸入,並返回主要的2D數組使用的兩個坐標。

請告訴我,如果我感到困惑或者我沒有意義,我會嘗試更好地解釋。

如果沒辦法這樣做,請告訴我。 JimiiBee

您可以返回一個2元素數組,將值連接到由分隔符分隔的字符串中,或​​者創建一個包含x和y坐標的Dimension類。

String promptCoords()
{
    return promptX() + ":" + promptY();
}

int[] promptCoords()
{
    return new int[]{promptX(), promptY()};
}

Dimension promptCoords()
{
    return new Dimension(promptX(), promptY());
}

private class Dimension 
{
    int x, y;

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

int promptX(){return -1;}
int promptY(){return -1;}

這里有很多資源可以實際獲取用戶輸入。 看看這篇文章 創建數組我會做這樣的事情:

public int[] getCoord(int[] coords) {
    coords[0] = getInt("Please enter x coordinate:");
    coords[1] = getInt("Please enter y coordinate:");
    return coords;
}

這將被稱為這樣:

coords = getCoord(coords);

哪個會用新值取代舊的coords值。

getInt方法如下所示:

private int getInt(String prompt) {
    Scanner scanner = new Scanner(System.in);
    System.out.println(prompt);

    int in = scanner.nextInt();
    scanner.close();
    return in;
}

當然,這可以合並為單個方法,避免重復打開和關閉掃描程序,但如果您在代碼中的其他位置使用getInt() ,這可能仍然是首選解決方案。

如果您被迫使用單獨的方法,我們寧願不必重復打開和關閉掃描儀,而是從getCoord類傳遞掃描儀。

public int[] getCoord(int[] coords) {
    Scanner scanner = new Scanner(System.in);
    coords[0] = getX(scanner, coords);
    coords[1] = getY(scanner, coords);
    scanner.close()
    return coords;
}

並舉例說明get方法:

private void getX(Scanner scanner, int[] coords) {
    System.out.println("Please enter x coordinate:");
    coords[0] = scanner.nextInt(); //Change 0 index to 1 for getY
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM