簡體   English   中英

帶輸入值的2d布爾數組

[英]2d boolean array with input values

我已經創建了這段代碼(在Reimeus的幫助下)。 我將如何實現而不是用true替換數組中的每個值,而只替換一個預先確定的(例如z),並且這總是在2d數組的頂部列上的值。 此外,我想我應該如何開始得到而不是輸出是真的和假的它是x為真和y為假但仍然保持數組為布爾

import java.util.*;

class Main {
    public static void main(String[] args) {
        int x;
        int y;
        Scanner scanner;
        scanner = new Scanner(System.in);
        x = scanner.nextInt();
        y = scanner.nextInt();
        boolean[][] cells = new boolean[x][y];

        for (int i = 0; i < cells.length; i++) {
            Arrays.fill(cells[i], true);
           System.out.println(Arrays.toString(cells[i]));
        }
    }
}

使用Arrays.toString顯示數組內容,否則將顯示Object數組的Object#toString表示

System.out.println(Arrays.toString(cells[i]));

除了Reimeus回答:

如果我只想讓數組中的一個數組成為真,那​​么我需要做什么才能確定應該采用與確定數組長度相同的方式。

使用boolean數組默認填充false值的事實你只需要讀取一次應該設置為true的元素的索引,就像你使用length s一樣

boolean[][] cells = new boolean[x][y];

int trueX = scanner.nextInt();
int trueY = scanner.nextInt();
cells[trueX][trueY] = true;

也不要忘記刪除Arrays.fill(cells[i], true);


其次是有一種方法可以用“*”替換真實的語句,用“ - ”替換錯誤的語句

您可以創建第二個循環,它將遍歷行的元素,如果它的值為true打印*如果不是-就像在此代碼中一樣:

for (int i = 0; i < cells.length; i++) {
    for (int j = 0; j < cells[i].length; j++) {
        if (cells[i][j])
            System.out.print("* ");
        else
            System.out.print("- ");
    }
    System.out.println();
}

或者只是將Arrays.toString()的結果中的"true"字符串替換為* ,將"false"替換為"-"

for (int i = 0; i < cells.length; i++) {
    System.out.println(Arrays.toString(cells[i]).replace("true", "*")
            .replace("false", "-"));
}

暫無
暫無

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

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