我很新的編碼,只有有限的知識在VB中。我試圖在java中捕獲這些知識,並試圖創建一個簡單的搜索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)
我使用搜索功能找不到太多關於我的問題,即使它看起來像一個簡單的問題。
有可能是一個更簡單的方法來做我想做的事情,我會對此感興趣,但我也想知道爲什麼我的方法不工作。
你可能錯過了數組在Java中是零索引? – Erik
請勿使用String [] [] beer'。用'String name','int quantity'字段讓自己成爲'Beer'類。 – artbristol