2013-02-22 130 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); 
    } 
}