简体   繁体   English

如何使用 arrays 创建方法?

[英]How do you create methods using arrays?

How do you create a method that accepts a one-dimensional array and a string as its arguments?如何创建一个接受一维数组和字符串作为其 arguments 的方法?

  • Use a linear search to identify if the product is in the array.使用线性搜索来确定产品是否在数组中。 If the name is in the array, the method should return the position.如果名称在数组中,则该方法应返回 position。 If the number is not in the array, the method should return-1.如果该数字不在数组中,则该方法应返回-1。

  • When the user enters the name of a product, the program should step through the ArrayList.当用户输入产品名称时,程序应单步执行 ArrayList。

public static void main(String[] args) {

    ArrayList<String> products = new ArrayList<>();

    products.add("Pencil pouch");
    products.add("pen");
    products.add("Pencil sharpener");
    products.add("High lighters");
    products.add("Markers");
    products.add("Erasers");
    products.add("Binder");
    products.add("Notebooks");
    products.add("Index cards");
    products.add("Folders");
    products.add("Glue");
    products.add("Ruler");
    products.add("Scissors");
    products.add("Calculator");
    products.add("Calendar");
    products.add("Backpack");

    for (String i: products) {
        System.out.println(i);
    }
}

public static int searchProducts(int[] products) {
    System.out.println("enter all names of product");

    Scanner input = new Scanner(System.in);
    String x = input.nextLine();

    for (i = 0; i < products.length; i++){
        if (products][i] == x)
        return i;

    }

    return -1;
}

Ok, you're using an ArrayList.好的,您使用的是 ArrayList。 To accept multiple parameters, take a look at this link: https://www.w3schools.com/java/java_methods_param.asp要接受多个参数,请查看此链接: https://www.w3schools.com/java/java_methods_param.asp

Regarding your method, you should accept 2 parameters, not 1. In addition, you should accept an ArrayList, not a 1D array, and it should be of type String, not int.关于您的方法,您应该接受 2 个参数,而不是 1 个。此外,您应该接受 ArrayList,而不是一维数组,它应该是 String 类型,而不是 int。 Your method should look something like this:您的方法应如下所示:

public int searchProducts(ArrayList<String> arr, String str) {
    // you don't need to create a scanner object because the string you 
    intend to use is a parameter of the method
    
    for(int i=0; i<arr.size(); i++) {
        if(arr.get(i).equals(str)) {
            return i;
        }
    }
    return -1;
    
}

So now, if you want to call the method in your main(), you have to pass in your products ArrayList and the item you desire to find.所以现在,如果你想调用 main() 中的方法,你必须传入你的产品 ArrayList 和你想找到的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM