gpt4 book ai didi

java - 网格以及 x 和 y 坐标

转载 作者:行者123 更新时间:2023-12-01 04:50:41 25 4
gpt4 key购买 nike

我需要制作一个网格,用户在列和行中输入星号的数量,到目前为止我有这个:

import java.util.Scanner;

public class Grid {

public void run(){

Scanner scan = new Scanner(System.in);

System.out.println("Enter the grid width (1-9):" );
double num = scan.nextDouble();


System.out.println("Enter the grid length (1-9)");
double numLength = scan.nextDouble();


for(int i = 0; i < num; i++){
for(int j = 0; j < numLength; j++){
System.out.print("*");
}
System.out.println("");

但我不知道如何将字符“X”插入网格的左上角(0,0),也不知道如何使其移动甚至循环。用户必须输入“上”“下”“左”和“右”才​​能使其移动,我对如何在java中拥有x和y坐标感到非常困惑。

最佳答案

System.out 是一个简单的输出流。您无法在那里设置文本动画,也无法在命令行上注册方向键。

您需要一个 GUI。这不是最好的,但看看 Swing .

一种更困惑的方法是重复循环并通过命令行从用户输入中获取输入:

Scanner scan = new Scanner(System.in);

System.out.println("Enter the grid width (1-9):" );
int w = scan.nextInt();

System.out.println("Enter the grid length (1-9):");
int h = scan.nextInt();

int x = 0, y = 0;
while (true)
{
for(int i = 0; i < w; i++){
for(int j = 0; j < h; j++){
if (i != x || j != y)
System.out.print("*");
else
System.out.print("X");
}
System.out.println("");
}
System.out.println("Enter direction (u,d,l,r):");
char c = scan.next().charAt(0);
switch (c)
{
case 'u': x = Math.max(0, x-1); break;
case 'd': x = Math.min(w-1, x+1); break;
case 'l': y = Math.max(0, y-1); break;
case 'r': y = Math.min(h-1, y+1); break;
case 'x': System.out.println("Exiting..."); System.exit(0);
}
}

关于java - 网格以及 x 和 y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15019100/

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