2017-10-13 58 views
1

我不確定要在我的二維數組中的某個位置查找字符時需要使用什麼。我所試圖做的是讓用戶輸入的行數和列數和獲取價值的通訊員到二維數組中的兩個變量,檢索,然後它的陣列嘗試使用java中的行號和列號在二維數組中找到一個字符

 import java.util.*; 
public class twoDimension { 
    public static void printRow(int[] row) { 

     for (int i : row) { 
      System.out.print(i); 
      System.out.print("\t"); 
      } 
     System.out.println(); 
     } 

    public static void main(String[] args) { 
     int twoDm[][]= new int[3][4]; 

     for (int i = 0; i < twoDm.length; i++) { 
      for (int j = 0; j < twoDm[i].length; j++) { 
       twoDm[i][j] = (int)(Math.random()*10); // we decided to randomise the numbers in the array. 
       } 
      } 

     for(int[] row : twoDm) { 
      printRow(row); 
      } 

     System.out.println("Enter a number with the format 'xy'. x is the row number and y the column number. Whenever you want to quit out, input 'quit'."); 
     String xy; 
     while (!xy.equalsIgnoreCase("quit")) { 
      Scanner scanner = new Scanner(System.in); 
      String xy = scanner.nextLine(); 
      char x = xy.charAt(0); 
      char y = xy.charAt(1); 
      // fetching the character in the array and displaying it 
      // setting it to 0 
      // displaying the array again 
      } 
     } 
    } 

中設置爲0 PS:我設法找到了如何在沒有逗號或括號的情況下顯示數組,但我不確定是否要移除顯示中的空格。

+0

通過「空格在顯示「你的意思是由'System.out.print(」\ t「)''創建的標籤嗎? –

+0

是的,我做,對不起 – Dracose

回答

1

如果你把xy座標整數:

int xCoor = Character.getNumericValue(x); 
int yCoor = Character.getNumericValue(y); 

那麼你就可以訪問和/或使用這些座標修改數組:

twoDm[xCoor][yCoor] = 0; 
+0

編譯器帶來了這個:char不能轉換爲字符串 \t \t \t int xCoor = Integer.parseInt(x); – Dracose

+1

@Dracose對不起,我認爲'x'和'y'是'String'的值。我更新了我的答案來解決這個問題。 –

+1

@Dracose如果這個答案有效,請確保接受它以顯示它幫助你的社區。 –

相關問題