[英]If statements and searching String arrays using loops in Java
我對編碼還很陌生,並且對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)
盡管它看起來像是一個簡單的問題,但我使用搜索功能找不到關於我的問題的很多信息。
可能有一種更簡單的方法來執行我正在嘗試的操作,對此我會很感興趣,但是我也想知道為什么我的方法無法正常工作。
數組索引的范圍是0
到N - 1
,其中N
是數組中元素的數量。 因此,索引2
是具有2
元素的數組的末尾:
System.out.println(beer[tempNum][2]);
// ^ only 0 and 1 are valid.
請注意, tempNum
從數組中的第二個元素開始,並且啤酒的名稱實際上在beer[tempNum][0]
。
有關更多信息,請參見Java Language Specification的Arrays一章。
只需提及擴展的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);
}
在詢問其他解決方案的部分中,可以嘗試以下操作:
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.
}
}
遵循oracle網站上的教程將非常高興。 它們非常好,您將很快學習Java基礎。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.