好的,所以这是我的代码(我试图调用的主要方法和方法) 我希望我的方法“rotateRR”基本上从board [0]获取值并将其置于[1]并继续为该单行执行该操作。例如:
旧数组 - > [1] [2] [3] [4] [5]成为[5] [1] [2] [3] [4]< - 新的数组应该是什么样的。
但在我调用我的方法后,我将常规输入设置为“1 rr”,但它返回相同的数组。我需要从rotateRR方法返回更新的数组,但它不允许我添加一个return语句。
公共课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
答案 0 :(得分:1)
该方法的主要问题是它甚至没有执行您所描述的功能:
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;
}
因此,在该方法之后,作为参数插入的数组将按照上述方式进行更改。请注意,您不需要返回类型,因为更改会影响原始数组(关键字call-by-reference)。
答案 1 :(得分:0)
您已经创建了函数void
,因此您无法从中返回任何内容。所以你需要做的是将它从void更改为char *之类的东西,然后返回相关的char *来解决你的问题
阅读本文:http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html以获得更多疑问。
答案 2 :(得分:-1)
改变这个:
public static void showBoard()
到这个
public static return-type showBoard()