1

ユーザーが列と行にアスタリスクの数を入力するグリッドを作成する必要があります。これまでのところ、次のようになっています。

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座標を設定する方法については非常に混乱しています。

4

1 に答える 1

0

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);
   }
}
于 2013-02-22T07:51:08.007 に答える