简体   繁体   中英

If statements and searching String arrays using loops in Java

I'm pretty new to coding and only have limited knowledge in 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.

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. So an index of 2 is one past the end of an array that has 2 elements:

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

Refer to the Arrays chapter of the Java Language Specification for more information.

Just to mention the extended for loop that you can use to iterate over the array:

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<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. They are quite good and you will learn the basics of java really fast.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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