搜索二维字符串数组并输出位置

时间:2013-12-09 00:11:16

标签: java arrays search 2d

所以,我有这个数组:

    String HomeDepot[][] = {
    {"Refridgerators", "Washers", "Dryers", "Dishwashers", "Vaccum Cleaners", "Fans", "Small Appliances"},
    {"Sinks", "Tubs", "Showers", "Toilets", "Facuets"},
    {"Lumber", "Doors", "Windows", "Drywall", "Fireplaces", "Ladders", "Insulation", "Decking", "Hardware"},
    {"Blinds", "Rugs", "Shelves", "Mirrors", "Wallpaper", "Furntiture"},
    {"Wire", "Heaters", "Light Bulbs", "Smoke Alarms", "Extension Chords"},
    {"Flooring" , "Tile", "Laminate", "Hardwood"},
    {"Cabinets", "Bookcases", "Door Knobs"},
    {"Chandeliers", "Lamps", "Outdoor Lighting", "Lamp Shades"},
    {"Paint", "Brushes", "Spray Paint", "Paint Samples", "Wood Stain"},
{"Power Tools", "Tool Accessories", "Tool Storage"}
    };

我想搜索用户提示的查询(如下所示):

    String item;
    item = JOptionPane.showInpuDialog("What would you like to search for? Please capitalize your query.");

我似乎无法让它发挥作用!我希望它能够在数组中搜索用户的项目,并找到它。输出项目的位置。如果该项不在数组中,我希望它询问用户是否想再次搜索,或者放弃。请帮忙!我正在使用java。

1 个答案:

答案 0 :(得分:0)

尝试:

String item;
int[] coords = new int[2];

boolean finished = false;
while(!finished){ // if we don't find what you searched, then keep checking
   item = JOptionPane.showInputDialog("What would you like to search for?");
   for(int i = 0; i < HomeDepot.length; i++) { 
       for(int j = 0; j < HomeDepot[i].length; j++) {
           if(HomeDepot[i][j].equals(item)) {
               coords[0] = i;
               coords[1] = j;
               finished = true;
           }
           if(finished) break; 
       } 
       if(finished) break;
   }
   if(!finished)
      System.out.println("Could not find " + item + "! Please try again.");
}
System.out.println(coords[0] + "," + coords[1]); // prints the location once you've
                                                 // searched a valid String in the matrix

这将为您提供包含项目行和列的元组(如果存在)。