比方說,我得到這個地圖打印出:如何更改二維數組中數組元素的值?
00000
00000
00000
如何改變元素[0] [0]到X?
換句話說,如何使它看起來像這樣使用屏幕輸入:
X0000
00000
00000
比方說,我得到這個地圖打印出:如何更改二維數組中數組元素的值?
00000
00000
00000
如何改變元素[0] [0]到X?
換句話說,如何使它看起來像這樣使用屏幕輸入:
X0000
00000
00000
考慮它的2D Array
String
的類型...
arr[0][0] = "X";
運行以下命令:
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("");
}
}
}
謝謝! 但是如果我想通過使用屏幕輸入來編輯[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();
}
}
}
'矩陣[0] [0] = X' ?? – Nishant
-1爲基本問題。如果你知道什麼是數組,那麼不僅僅是打開每本Java書籍或者教程甚至是谷歌它,答案都會直接跳到你身上。我不喜歡說RTFM,但在這種情況下,這是你應該做的。 – popfalushi
[你有什麼嘗試?](http://www.whathaveyoutried.com) –