我创建了一个二维数组,我需要在该数组中搜索状态缩写,如果找到,那么我需要打印它所找到的行。我确实为此创建了一个单独的方法。我正在传递一个两个字母的州名缩写,我在我的主要内容中要求。我搜索了其他论坛,但我看到的所有问题都与此类问题无关。很多我发现的是找到重复或发现打印索引,但不是行。感谢您的帮助。
private static void ticketpayout(String state) {
// search array for state
//2d array with all state info
String[][] tax = {
{"AZ", "5%", "Annually", "$2,823,333", "After 30 Years", "$84,699,990", "Cash", "$57,050,000"},
{"AR", "7%", "Annually", "$2,742,667", "After 30 Years", "$82,280,010", "Cash", "$55,420,000"},
{"CO", "4%", "Annually", "$2,863,667", "After 30 Years", "$85,910,010", "Cash", "$57,865,000"},
{"CT", "6.7%", "Annually", "$2,754,767", "After 30 Years", "$82,643,010", "Cash", "$55,664,500"},
{"DE", "0%", "Annually", "$3,025,000", "After 30 Years", "$90,750,000", "Cash", "$61,125,000"},
{"FL", "0%", "Annually", "$3,025,000", "After 30 Years", "$90,750,000", "Cash", "$61,125,000"},
{"GA", "6%", "Annually", "$2,783,000", "After 30 Years", "$83,490,000", "Cash", "$56,235,000"},
{"ID", "7.8% ", "Annually", "$2,710,400", "After 30 Years", "$81,312,000", "Cash", "$54,768,000"},
{"IL", "5%", "Annually", "$2,823,333", "After 30 Years", "$84,699,990", "Cash", "$57,050,000"},
};
}
答案 0 :(得分:3)
您可以像这样搜索2D数组:
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < colLength; j++) {
if (tax[i][j].equals(state))
printArray(tax, i);
}
}
public static void printArray(String[][] array, int row) {
for(int i = 0; i < rowLength; i++)
System.out.print(array[row][i] + " ");
}
要回答@ Tree的问题,请检查两行是否相等:
public static boolean rowEquals(String[] one, String[] two) {
for(int i = 0; i < one.length; i++)
if(!one[i].equals(two[i]))
return false;
return true;
}
答案 1 :(得分:0)
要直接回答您的问题,您可以遍历tax
数组,检查每个元素,如下所示;
private static String[][] tax = ...;
private static String[] ticketpayout(String state) {
for (String[] taxRow : tax) {
if (taxRow[0].equals(state)) {
return taxRow;
}
}
return null;
}
但是,我不认为这是你想要解决的问题的最佳类设计。最好从这里的数据中创建一个对象,并根据状态缩写将它们添加到Map中,如下所示:
public class TaxInfo {
String state;
double taxRate;
Period period;
etc...
enum Period {
ANNUALLY,
MONTHLY,
etc...
}
}
private static Map<String, TaxInfo> tax = new HashMap<String, TaxInfo>();
private static void populateTaxInfo() {
tax.put("AZ", new TaxInfo("AZ", 5, TaxInfo.Period.ANNUALLY, ...));
tax.put("AR", new TaxInfo("AR", 7, TaxInfo.Period.ANNUALLY, ...));
tax.put("CO", new TaxInfo("CO", 4, TaxInfo.Period.ANNUALLY, ...));
...
}
然后检索记录,只需例如tax.get("AZ");
答案 2 :(得分:0)
您需要搜索[0] [1] [0] [2] ..等等,直到找到您正在寻找的内容...
你可以做嵌套for循环。也搜索这个网站,我确定有搜索示例。
您还应该发布您尝试过的内容,以便我们为您提供帮助。