搜索数组,并输出元素编号

时间:2015-05-20 14:46:15

标签: java arrays search

我正在编写一个程序,允许用户输入数组中列出的任何项目,并输出该项目的元素编号。

public static void main(String[] args) {

    String[] menu = {"apples", "bananas", "pears", "milk", "cookies", "bread", "lemons"};

    Scanner user_input = new Scanner(System.in);

    String item;
    item = user_input.next();

我怎么能这样做?

4 个答案:

答案 0 :(得分:0)

试试这个:

for(int i = 0; i < menu.length; i++){
  if(menu[i].equalsIgnoreCase(item)){
    //Do what you want with i as the index.
    break;
  }
}

这循环遍历数组以找到与搜索过的匹配的那个。

答案 1 :(得分:0)

让我们试试这个:

import java.io.IOException;
import java.util.Scanner;

public class Stack {

    public static void main(String[] args) throws IOException {
        String[] menu = {"apples", "bananas", "pears", "milk", "cookies", "bread", "lemons"};

        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enater a value to search : ");

        String user_input  = keyboard.next();

        boolean found=false;
        int location = 0;

        for(int i=0;i<menu.length;i++)
        {
            if(menu[i].equalsIgnoreCase(user_input))
            {
                found=true;
                location = i;
            }
            else
            {
                continue;
            }
        }
        if(found)
        {
            System.out.println("String found at location : " +location);
        }
        else
        {
            System.out.println("String not found!");
        }
    }
}

希望它有所帮助!

答案 2 :(得分:0)

   import java.util.Scanner;

   public class MenuCard {

   public static void main(String[] args) {



        String[] menu = {"apples","apples", "bananas", "pears", "milk", "cookies", "bread", "lemons"};

        int count=0;

        Scanner user_input = new Scanner(System.in);
        System.out.println(" type any item to check in menu");
        String item;
        item = user_input.next();
        for(String s:menu)
        {
              if(s.equalsIgnoreCase(item))
              {
                  count++;

              }

        }
        System.out.println("no. of item is "+count);
        }
    }

答案 3 :(得分:0)

为什么不使用库方法?

import java.util.Arrays;
import java.util.Scanner;

public class MenuCard {

    public static void main(String[] args) {

        String[] menu = { "apples", "apples", "bananas", "pears", "milk",
                "cookies", "bread", "lemons" };

        Scanner user_input = new Scanner(System.in);
        System.out.println(" type any item to check in menu");
        String item;
        item = user_input.next();
        int count = Arrays.asList(menu).indexOf(item.toLowerCase());
        if(count < 0)
            System.out.println("Item not found");
        else
            System.out.println("no. of item is " + count);
    }
}

首先,您通过Arrays.asList将数组转换为List,然后使用List.indexOf方法。查找列表元素的索引。