2013-02-22 96 views
1

我需要在用户输入的行和列的星号数的网格,到目前为止,我有这样的:电网和x和y坐标

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(""); 

,但我不知道该怎么在网格的(0,0)中插入一个字符'X',左上角或如何使其移动,甚至可以循环。用户必须放置“向上”“向下”“左”和“右”才​​能移动,并且我非常困惑于如何在java中使用x和y坐标。

+0

里面你的循环,'x'是'j'和'y'是'我'。就如此容易。 – 2013-02-22 07:40:30

回答

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); 
    } 
}