gpt4 book ai didi

java - 更改数组中的值

转载 作者:太空宇宙 更新时间:2023-11-04 15:07:20 25 4
gpt4 key购买 nike

好的,这是我的代码(主要方法和我试图调用的方法)我希望我的方法“rotateRR”基本上从 board[0] 获取值并将其放在 [1] 上,并继续对单行执行此操作。例如:

旧数组 -> [1][2][3][4][5] 变为 [5][1][2][3][4] <- 新数组应该是什么样子。

但是在我调用我的方法之后,我输入的常规输入应该是“1 rr”,但它返回相同的数组。我需要从rotateRR 方法返回更新后的数组,但它不允许我添加返回语句。

公共(public)课Numbrosia { static int [][] board = new int[5][5];

public static void main(String [] args){
Scanner scan = null;

try{
scan = new Scanner(new File("input.txt"));
}
catch (FileNotFoundException e){
e.printStackTrace();
return;

}

for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = scan.nextInt();

}
}


Scanner input = new Scanner (System.in);
while (true){
showBoard();

System.out.println("What's your move?");
int rowOrCol = input.nextInt();
String action = ("");
action = input.nextLine();

if (action.equals(rowOrCol + " rr")){
rotateRR(board);
System.out.println("The new board looks like: ");
//Im guessing I should put something here?
}

}

}

public static void showBoard(){
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board.length; col++){
System.out.print(board[row][col] + " ");
}
System.out.println(" ");

}



}

//METHODS

public static void rotateRR (int [][] board){
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}
//Its not letting me add a "return" type, tells me it is a syntax error on and an invalid type

最佳答案

该方法的主要问题是它甚至没有执行您所描述的功能:

public static void rotateRR (int [][] board){ 
int[] temp = board[0];
for (int i = 0; i < board.length + 1; i++){
board[i] = board[i+1];
}
board[board.length + 1] = temp;
}

应改为:

public static void rotateRR (int [][] board){ 

// Saves the last entry of board, because
// each entry should be shifted to the right
int[] temp = board[board.length - 1];

// Here you should only run till board.length - 2, because
// if you add 1 to i for accessing the next entry
// you can maximal access the entry with number board.length - 1
for (int i = 0; i < board.length - 1; i++){
board[i] = board[i+1];
}

// Set the first entry to temp
board[0] = temp;
}

因此,在该方法之后,您作为参数插入的数组将按照您上面描述的方式进行更改。请注意,您不需要返回类型,因为更改会影响原始数组(关键字按引用调用)。

关于java - 更改数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21808764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com