if语句和使用Java中的循环搜索String数组

Sir*_*dgy 2 java arrays string loops if-statement

我对编码很陌生,对vb的了解有限.我正试图在java中捕获这些知识,并且我正在尝试创建一个简单的搜索java程序,该程序根据输入搜索数组并输出信息以帮助了解循环和多维数组.

我不确定为什么我的代码不起作用,

package beers.mdarray;

import java.util.Scanner;

public class ProductTest
{
    public static void main(String[] arg)
    {
        String [][] beer = { {"TIGER", "2"}, {"BECKS", "2"}, {"STELLA", "3"} }; //creating the 2 by 3 array with names of beer and their corresponding stock levels.
        System.out.print("What beer do you want to find the stock of?: ");

        Scanner sc = new Scanner(System.in);
        String beerQ = sc.next(); // asking the user to input the beer name

        int tempNum = 1;
        if (!beerQ.equals(beer[tempNum][1]))
        {
            tempNum = tempNum + 1; //locating he location of the beer name in the array using a loop to check each part of the array.
        }
        System.out.println(beer[tempNum][2]); //printing the corresponding stock.
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出,但我不知道这意味着什么:

What beer do you want to find the stock of?: BECKS
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at beers.mdarray.ProductTest.main(ProductTest.java:20)
Run Code Online (Sandbox Code Playgroud)

即使它看起来像一个简单的问题,我也无法使用搜索功能找到我的问题.

可能有一种更简单的方法来做我正在尝试的事情,我会对此感兴趣,但我也想知道为什么我的方法不起作用.

hmj*_*mjd 5

数组索引从0to 运行N - 1,其中N是数组中元素的数量.所以索引2是一个超过数组结尾的索引2:

System.out.println(beer[tempNum][2]);
                              // ^ only 0 and 1 are valid.
Run Code Online (Sandbox Code Playgroud)

请注意,tempNum启动是从数组中的第二个元素开始,啤酒的名称实际上是beer[tempNum][0].

有关更多信息,请参阅Java语言规范的数组章节.

只是提到可以用来迭代数组的扩展for循环:

String [][] beers = { {"TIGER",  "2"},
                      {"BECKS",  "2"},
                      {"STELLA", "3"} }; 

for (String[] beer: beers)
{
    if ("BECKS".equals(beer[0]))
    {
        System.out.println(beer[1]);
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用多维数组的替代方法是使用其中一个Map实现,其中啤酒的名称是关键,而库存水平是值:

Map<String, Integer> beers = new HashMap<String, Integer>();
beers.put("TIGER",  9);
beers.put("BECKS",  2);
beers.put("STELLA", 3);

Integer stockLevel = beers.get("BECKS");
if (stockLevel != null)
{
    System.out.println(stockLevel);
}
Run Code Online (Sandbox Code Playgroud)