在Java中使用多维数组

时间:2015-12-12 20:14:01

标签: java arrays multidimensional-array

我正在向用户展示一系列可供选择的葡萄酒。葡萄酒种类(雷司令,霞多丽等)有葡萄酒的变化。我想向用户显示整个葡萄酒菜单,然后输入1-4以指示他们想要的类型,其中显示了该列的所有行。然后,他们可以输入1-3来选择他们想要的行。我的问题是,我不知道如何为此制定方法。此外,用户最多可以执行此操作16次,或直到他们希望退出。不过,这只是一种方法。任何可以提供帮助的人都将不胜感激。

http://puu.sh/lT5r5/4b7fd3262d.png(提示)

import javax.swing.JOptionPane;

public class WineCalc{

public static void main(String[] args){

  String[][]wineTypes = {
                        {"Riesling", "Chardonnay", "Sauvignon Blanc", "Merlot"},
                        {"Dry- $4.50", "Apple- $6.00", "Lime-$4.50", "Plum- $5.00"},
                        {"Off Dry-$4.00", "Lemon-$5.50", "Lemongrass- $6.50", "Black Cherry- $7.50"},
                        {"Sweet- $5.00", "Vanilla- $6.00", "Coconut- $7.00", "Chocolate- $6.00"},
                        };
  double[][]prices = {
                     {4.50, 6.00, 4.50, 5.00},
                     {4.00, 5.50, 6.50, 7.50},
                     {5.00, 6.00, 7.00, 6.00},
                     };

  int[][]counter = {
                   {0,0,0,0},
                   {0,0,0,0},
                   {0,0,0,0},
                   };


}

public static String getWineType(String wineTypes[][]){
  for(i=0; i<wineTypes[0].length;i++){
     for(int j=0; j<wineTypes.length; j++){
        JOptionPane.showMessageDialog(null, wineTypes[i][j]);
   }
  }




return wineTypes[][];
}
}

1 个答案:

答案 0 :(得分:1)

您宣布您的2D阵列很好,但您的方法需要重新加工。你给它一个字符串返回类型但没有返回任何东西,将其改为void。

获取输入:

// somewhere before the getWineType() call
int i = Integer.parseInt(JOptionPane.showInputDialogue("Enter First number: ")
// if you want to list all the wines in the sub query at this point put a method here to do so
int j = Integer.parseInt(JOptionPane.showInputDialogue("Enter Second number: ")
JOptionPane.showMessageDialog(wineTypes[i][j]); //this will show the selected wine

至于你的列表葡萄酒方法。

public static void listWineTypes(wineTypes[][]) {  //void return
       listarray[][] = wineTypes[][]; 
      for(i=0; i<listarray.length;i++){  //change this
        for(int j=0; j<listarray[i].length; j++){ //and this
          JOptionPane.showMessageDialog(wineTypes[i][j]); //this will print out each wine in the list.
}

您还必须在某个地方调用该方法:

     getWineType(wineType[][]);