简体   繁体   English

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

[英]If statements and searching String arrays using loops in Java

I'm pretty new to coding and only have limited knowledge in vb. 我对编码还很陌生,并且对vb的了解有限。 I'm trying to catch that knowledge up in java and am trying to create a simple search java program that searches an array based on an input and outputs information to help learn about loops and multi dimensional arrays. 我试图在Java中掌握这些知识,并试图创建一个简单的搜索Java程序,该程序根据输入来搜索数组并输出信息以帮助了解循环和多维数组。

I'm not sure why my code won't work, 我不确定为什么我的代码无法正常工作,

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

This is what I get for output however and I'm not sure what it means: 这是我得到的输出,但是我不确定这意味着什么:

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)

I couldn't find much about my question using the search function even though its seems like a simple problem. 尽管它看起来像是一个简单的问题,但我使用搜索功能找不到关于我的问题的很多信息。

There is probably an easier way to do what I am attempting and I would be interested in that, but I also want to know why my method isnt working. 可能有一种更简单的方法来执行我正在尝试的操作,对此我会很感兴趣,但是我也想知道为什么我的方法无法正常工作。

Array indexes run from 0 to N - 1 , where N is the number of elements in the array. 数组索引的范围是0N - 1 ,其中N是数组中元素的数量。 So an index of 2 is one past the end of an array that has 2 elements: 因此,索引2是具有2元素的数组的末尾:

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

Note that the initilization of tempNum is starting at the second element in the array and the name of the beer is actually in beer[tempNum][0] . 请注意, tempNum从数组中的第二个元素开始,并且啤酒的名称实际上在beer[tempNum][0]

Refer to the Arrays chapter of the Java Language Specification for more information. 有关更多信息,请参见Java Language Specification的Arrays一章。

Just to mention the extended for loop that you can use to iterate over the array: 只需提及扩展的for循环,即可用于遍历数组:

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

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

Alternative to using a multi-dimensional array would be to use one of the Map implementations, where the name of the beer is the key and the stock level is the value: 使用多维数组的替代方法是使用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);
}

In the part where you are asking another solution to your problem you can try the below: 在询问其他解决方案的部分中,可以尝试以下操作:

package com.nikoskatsanos.playground;

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

        boolean found = false;
        int index = 0;
        while(!found) {
            if(beer[index][0].equals(beerQ.toUpperCase())) {
                found = true;
                continue;
            }
            index ++;
        }
        System.out.println("The stock of " + beerQ + " is " + beer[index][1]); //printing the corresponding stock.
    }
}

It would be nice for you to follow the tutorials in oracle's web site. 遵循oracle网站上的教程将非常高兴。 They are quite good and you will learn the basics of java really fast. 它们非常好,您将很快学习Java基础。

http://docs.oracle.com/javase/tutorial/ http://docs.oracle.com/javase/tutorial/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM