【问题标题】:Incompatible types error when trying to pass a 2d array尝试传递二维数组时出现不兼容类型错误
【发布时间】:2019-11-08 09:20:04
【问题描述】:

我正在尝试将二维数组传递给另一个方法,但它一直给我错误“int 无法转换为 int[][]”,而返回行则相反。当我从 Deal 方法中删除 [][] 时,它给了我错误,但反过来说“int [] [] 无法转换为 int”。我在这里做错了什么?

//2-6 players face eachother in a game of Go Fish!

import java.util.Scanner;
import java.lang.String;
import java.util.Random; //RNG

public class GoFish{
public static void main(String []args){
   Scanner in = new Scanner(System.in);
   System.out.println("This is a game simulation of Go Fish! It supports up to 6 players.");
   int Players = 0;
   System.out.println("How many players will be playing?");
   Players = in.nextInt();          //# of players
   while(Players < 2 || Players > 6){
      System.out.println("Please enter a number of players, between 2 and 6");
      Players = in.nextInt();
   }
   int [][] Cards = new int[Players + 1][54]; //Array for the cards. Final entry is the number of cards within the hand/deck, second to last number is the number of points.
   String [] Deck = new String [52];//This Array will contain the name for each card.
   Cards [0][52] = 52;              //Array 0 is the deck, Array 1 is the hand for player 1, Array 2 is the hand for player 2, ect.
   for(int i = 0; i < 52; i++){     //Fill the deck with cards.
      Cards [0][i] = 1;
   }
   int n = 5;                       //Number of cards to deal to the users.
   if(Players == 2)
      n = 7;                        //Increases to 7 if only 2 players are playing.
   for(int i = 0; i < n; i++){      //Deal cards for both players.
      for(int j = 0; j < Players; j++){
         Cards = Deal(Cards, Deck, Players);
      }
   }
}

static int Deal(int Cards[][], String Deck[], int Players){
return Cards;
}
}

【问题讨论】:

  • Deal 应该做什么?
  • 现在什么都不做,以后会修改卡组中的牌,和正在抽牌的玩家的手,然后返回修改后的数组。
  • Deal的返回类型改为int[][],即static int[][] Deal(int Cards[][], String Deck[], int Players){ return Cards;}

标签: java arrays methods compiler-errors


【解决方案1】:

函数 Deal 返回 int 但您将 Cards 定义为:int [][] Cards。

【讨论】:

  • 如何返回int?方法内的卡片定义为 int Cards[][];返回行上的错误显示“不兼容的类型:int[][] 无法转换为 int”。如果修改返回行为“return Cards[][];”它给了我一个 .class 错误。编辑:我看到我的错误,我需要将 [][] 添加到函数本身,谢谢:)
  • @Surav:是的,看到错误非常令人困惑。我也很难在第一时间找到问题所在。
猜你喜欢
  • 2013-10-06
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
  • 2017-08-12
  • 2019-05-07
  • 2020-05-22
  • 2022-12-05
  • 2012-03-26
相关资源
最近更新 更多