gpt4 book ai didi

java - 随用户输入而变化的二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 13:07:42 24 4
gpt4 key购买 nike

我被要求制作一个程序来打印 5x5 网格,允许用户输入一个整数来确定“x”的放置位置。例如,如果用户输入 1,它将打印出来。

x 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

这是我的代码。我已经构建了数组,但我似乎无法让它打印出输入整数起作用的数组。另外,我是否会一次又一次地循环相同的代码,直到有人获胜或所有空格都被填满。

import java.util.Scanner;
public class Grade {

static Scanner input = new Scanner(System. in );
public static void main(String[] args) {
final int rows = 5;
final int columns = 5;
int one;
int two;

int[][] grid = new int[rows][columns];

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println("");

}

System.out.println("player one choose your position");
one = input.nextInt();

while (one > 25 || one < 1) {
System.out.println("error");
while (!input.hasNextInt()) {
input.next();
}
one = input.nextInt();
}

System.out.println("player two choose your position");
two = input.nextInt();

while (two > 25 || two < 1) {
System.out.println("error");
while (!input.hasNextInt()) {
input.next();
}
two = input.nextInt();
}

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println("" + one);
}
}
}

最佳答案

下面发布了执行您所要求的操作所需的代码。由于 x 是代码中的 int,因此您需要一种算法来实现它,以便您可以在 int[][] 中正确设置位置。

import java.util.Scanner;

public class GradeSO
{
Scanner input = new Scanner(System. in);

int remainder;
int down;
int column;
int row;

int rows = 5;
int columns = 5;
int one;
int two;

int[][] grid;

public void makeLocation(int x, int r, int c)
{
remainder = x % c;
down = (int) x / r;

if(x % c!=0)
{
column = remainder-1;
}
else
{
column = remainder;
}

if(x % c==0)
{
row=down-1;
column = remainder+4;
}
else
{
row=down;
}
}

public void makeArray()
{
grid = new int[rows][columns];

System.out.println("Player 1: Please chose a number between 1 and 25");
one = input.nextInt();

while (one > 25 || one < 1)
{
System.out.println("Error: Invalid Number");
System.out.println("Player 1: Please enter a number between 1 and 25");
while (!input.hasNextInt()) {
input.next();
}
one = input.nextInt();
}

makeLocation(one,columns,rows);
grid[row][column]= 1;

System.out.println("Player 2: Please chose a number between 1 and 25");
two = input.nextInt();

while (two > 25 || two < 1)
{
System.out.println("Error: Invalid Number");
System.out.println("Player 2: Please enter a number between 1 and 25");
while (!input.hasNextInt()) {
input.next();
}
two = input.nextInt();
}

makeLocation(two,columns,rows);
grid[row][column]= 2;
}

public void displayArray()
{
for (int[] smallGrid: grid)
{
for (int elem: smallGrid)
{
System.out.print(elem);
}
System.out.println();
}
}

public static void main(String[] args)
{
GradeSO gSO = new GradeSO();
gSO.makeArray();
gSO.displayArray();
}
}

关于java - 随用户输入而变化的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34272523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com