Java program to find the index of item entered by the user using method

huangapple go评论76阅读模式
英文:

Java program to find the index of item entered by the user using method

问题

import java.util.Scanner;

public class Example {
    static String[] cat = new String[5];  // Moved cat array to a higher scope
    
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        
        cat[0] = "Design";
        cat[1] = "Biology";
        cat[2] = "Business";
        cat[3] = "Health";
        cat[4] = "History";

        System.out.print("Enter Category: ");
        String e = in.nextLine();
        int index = new Example().Find(e);  // Pass the entered category to the Find method
        if (index != -1) {
            System.out.print("The index of " + e + " is: " + index);
        } else {
            System.out.print("Not found");
        }
    }

    public int Find(String e) {
        int index = -1;
        for (int i = 0 ; i < cat.length; i++) {
            if (cat[i].equals(e)) {
                index = i;
                break;  // Exit the loop once the category is found
            }
        }
        return index;  // Return the index after the loop completes
    }
}
英文:

How do I make a Java program that finds the index of any category entered by the user.

the method Find() receives the array and return the index of that specific category .The method should search in the array and print the index of the category if exists or “Not found" if not.

I wrote this code but I don't know how methods work exactly. I keep getting errors and I don't know how to fix them.

import java.util.Scanner;
public class Example {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String[] cat = new String[5];
        cat[0] = &quot;Design&quot;;
        cat[1] = &quot;Biology&quot;;
        cat[2] = &quot;Business&quot;;
        cat[3] = &quot;Health&quot;;
        cat[4] = &quot;History&quot;;

        System.out.print(&quot;Enter Category: &quot;);
        String e = in.nextLine();
        new Example().Find();
        System.out.print(&quot;The index of &quot; + cat[i] + &quot; is: &quot; + index);
    }

    public int Find() {
        int index = -1;
        for (int i = 0 ; i &lt; cat.length; i++) {
            if (cat[i].equals(e)) {
                index = i;
                return index;
            }
        }
    }
}

答案1

得分: 0

注意到了一些问题看起来你需要了解一下作用域 https://www.geeksforgeeks.org/variable-scope-in-java/ :

1. 需要将 e 传递给 Find 方法因为你在主函数中声明了它的局部变量
2. 需要在主函数中设置 index 变量
3. 你返回的索引是从 0 开始的所以不确定你是否希望是这样我的答案假设你不希望是从 0 开始的
4. 需要将 cat 数组传递给方法

```java
import java.util.Scanner;

public class Example {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String[] cat = new String[5];
        cat[0] = "Design";
        cat[1] = "Biology";
        cat[2] = "Business";
        cat[3] = "Health";
        cat[4] = "History";

        System.out.print("Enter Category: ");
        String e = in.nextLine();
        int index = Find(e, cat);
        System.out.print("The index of " + e + " is: " + index);
    }

    public static int Find(String e, String[] cat) {
        for (int i = 0; i < cat.length; i++) {
            if (cat[i].equals(e)) {
                return i + 1;
            }
        }
        return -1;
    }
}

<details>
<summary>英文:</summary>

Noticed a few thing. Looks like you need to read up on scope https://www.geeksforgeeks.org/variable-scope-in-java/:

1. Need to pass in e to find since you have it local to main
2. Need to set index variable in main.
3. Index you are returning is 0 based so not sure if you want that. My answer assumes you don&#39;t.
4. Need to pass in cat array

import java.util.Scanner;

public class Example {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String[] cat = new String[5];
cat[0] = "Design";
cat[1] = "Biology";
cat[2] = "Business";
cat[3] = "Health";
cat[4] = "History";

    System.out.print(&quot;Enter Category: &quot;);
    String e = in.nextLine();
    int index = Find(e);
    System.out.print(&quot;The index of &quot; + cat[i] + &quot; is: &quot; + index);
}

public int Find(String e, String [] cat) {
    int index = -1;
    for (int i = 0 ; i &lt; cat.length; i++) {
        if (cat[i].equals(e)) {
            return i+1;
        }
    }
}

}



</details>



# 答案2
**得分**: 0

你很接近了。以下是一种带有注释解释的方法来完成这个任务。

```java
    Scanner in = new Scanner(System.in);

    // 你初始化数组的方式是可以的,但是也可以使用下面这种更简单的方式。
    // String[] cat =  { "Design", "Biology", "Business", "Health", "History" };

    String[] cat = new String[5];
    cat[0] = "Design";
    cat[1] = "Biology";
    cat[2] = "Business";
    cat[3] = "Health";
    cat[4] = "History";

    System.out.print("输入类别:");
    String e = in.nextLine();

需要将类别字符串和数组传递给 `find` 方法。该方法将返回字符串在数组中的索引。

```java
    int index = new Example().find(e, cat);

现在验证索引是否有效。-1 表示未找到。其他任何值都应该提供在数组中的位置。

    if (index < 0) {
        System.out.println(e + " 未找到!");
    }
    else {

现在使用索引打印出对应的值。

        System.out.print(cat[index] + " 的索引是:" + index);
    }

这个方法几乎正确只需要将字符串和数组传递给 `find` 方法并且返回 `i` 对于索引已经足够了按照约定方法名应该以小写字母开头

```java
public int find(String str, String[] arr) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i].equals(str)) {
            return i;
        }
    }
    return -1;
}
英文:

You were close. Here is one way to do it with comments explaining things.

Scanner in = new Scanner(System.in);

// The way you initialzied your array is fine but you 
// could do the same thing like this which most times is easier.

// String[] cat =  { &quot;Design&quot;, &quot;Biology&quot;, &quot;Business&quot;, &quot;Health&quot;, &quot;History&quot; };

String[] cat = new String[5];
cat[0] = &quot;Design&quot;;
cat[1] = &quot;Biology&quot;;
cat[2] = &quot;Business&quot;;
cat[3] = &quot;Health&quot;;
cat[4] = &quot;History&quot;;

<!-- -->

System.out.print(&quot;Enter Category: &quot;);
String e = in.nextLine();

You need to pass the category string and the array to the find method. The method returns the index of the string in the array.

int index = new Example().find(e, cat);

Now verify the index is valid. A -1 means not found. Any other values should provide the location in the array.

if (index &lt; 0) {
    System.out.println(e + &quot; not found!&quot;);
}
else {

Now use the index to print out the value

    System.out.print(&quot;The index of &quot; + cat[index] + &quot; is: &quot; + index);
}

This method was find except for passing the string and the array to the find method. And returning i is sufficient for the index. And by convention, method names start with lower case letters.

public int find(String str, String[] arr) {
    for (int i = 0; i &lt; arr.length; i++) {
        if (arr[i].equals(str)) {
           return i;
        }
    }
    return -1;
}

huangapple
  • 本文由 发表于 2020年4月10日 01:09:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/61126523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定