java - Java 中使用循环的 if 语句和搜索字符串数组

标签 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.
    }
}

这是我得到的输出,但是我不确定它意味着什么:

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)

使用搜索功能我找不到太多关于我的问题的信息,尽管它看起来是一个简单的问题。

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

最佳答案

数组索引从 0N - 1,其中 N 是数组中元素的数量。因此,2 的索引是超过具有 2 元素的数组末尾的索引:

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

请注意,tempNum 的初始化是从数组中的第二个元素开始的,而啤酒的名称实际上位于 beer[tempNum][0] 中。

请参阅Arrays有关详细信息,请参阅 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;
    }
}

使用多维数组的替代方法是使用 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);
}

关于java - Java 中使用循环的 if 语句和搜索字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13490864/

相关文章:

c# - 将 "M/d/yyyy h:mm:ss tt"转换为 "YYYY-MM-DDThh:mm:ss.SSSZ"

javascript - 过滤字符串数组

java - 从代理获取已实现的接口(interface)

java - 小部件是什么意思并解释使用小部件

java - JHipster 6.0.1 docker-compose 部署 : Java heap space

java - 如何在Java中从文件中读取特定数量的字节到字节数组中?

java - JPA 避免在插入之前加载对象

vs2012 中的 c++/cli Windows 窗体,对象数组不可能

javascript - 将一个数组中的值分配给嵌套数组的最高效方法

c++ - 如何正确分割字符串中的数字?