2012-09-21 85 views
-1

比方说,我得到这个地图打印出:如何更改二维数组中数组元素的值?

00000 
00000 
00000 

如何改变元素[0] [0]到X?

换句话说,如何使它看起来像这样使用屏幕输入:

X0000 
00000 
00000 
+0

'矩阵[0] [0] = X' ?? – Nishant

+0

-1为基本问题。如果你知道什么是数组,那么不仅仅是打开每本Java书籍或者教程甚至是谷歌它,答案都会直接跳到你身上。我不喜欢说RTFM,但在这种情况下,这是你应该做的。 – popfalushi

+0

[你有什么尝试?](http://www.whathaveyoutried.com) –

回答

0

考虑它的2D ArrayString的类型...

arr[0][0] = "X";

0

运行以下命令:

import java.util.*; 
import java.lang.*; 

class Main 
{ 
     public static void main (String[] args) throws java.lang.Exception 
     { 
       String[][] array = {{"0","0","0"},{"0","0","0"},{"0","0","0"}}; 

       System.out.println("Before: "); 
       printArray(array); 


       array[0][0] = "x"; 
       System.out.println("After: "); 
       printArray(array); 

     } 

     private static void printArray(String[][] array){ 
       for(int i=0; i<array.length; i++){ 
         for(int j=0; j<array[0].length; j++){ 
           System.out.print(array[i][j]); 
         } 
         System.out.println("");   
       } 
     } 
} 

或去这里:http://ideone.com/2DQC1

+0

谢谢! 但是如果我想通过使用屏幕输入来编辑[0] [0]中的元素呢? –

0

在这个例子中用户k校验阵列元素值并改变它们

import java.util.Scanner; 

public class HelloWorld{ 

    public static void main(String []args){ 
     Scanner in = new Scanner(System.in); 
     int inputcol = 0; 
     int inputrow = 0; 
     int newnum = 0; 
     int uinput = 0; 
     int repeat = 1; 
     int[][] a = new int[][]{ 
     { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }, 
     { 110, 120, 130, 140, 150, 160, 170, 180, 190, 200 }, 
     { 210, 220, 230, 240, 250, 260, 270, 280, 290, 300 }, 
     { 310, 320, 330, 340, 350, 360, 370, 380, 390, 400 }, 
     { 410, 420, 430, 0, 440, 450, 460, 470, 490, 500 } 
     }; 
     while(repeat!=0) 
     { 
     System.out.println("Select Option:\n 1 for View Value:\n 2 for Replace Value: "); 
     uinput = in.nextInt(); 
     //int b[][]={{1,3,4},{3,4,5}}; 
     if(uinput==1) 
     { 
     System.out.println("Enter Row: "); 
     inputrow = in.nextInt(); 
     System.out.println("Enter Cols:"); 
     inputcol = in.nextInt(); 
     System.out.println(a[inputrow][inputcol]); 
     } 
     else 
     if(uinput==2) 
     { 
      System.out.println("Enter Row: "); 
     inputrow = in.nextInt(); 
     System.out.println("Enter Cols:"); 
     inputcol = in.nextInt(); 
     System.out.println("Enter New Number: "); 
     newnum = in.nextInt(); 
     a[inputrow][inputcol] = newnum; 
     } 
     else 
     { 
      System.out.println("Check your input. "); 
     } 
     System.out.println("Want to repeat it? if yes press 1\n for exit press 0 "); 
     repeat = in.nextInt(); 
     } 

    } 
}