You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断Scanner输入的字符串是否在数组中并实现对应输出?

Fixing Your Java Final Assignment Code

Hey there! I see you're working on your Java final assignment and need help wrapping up the code. Let's get this sorted out for you step by step.

First, let's recap what your code needs to accomplish:

  • Prompt the user to enter a string
  • Check if that string exists in the names array
  • If it does, output its index position
  • If not, output "NOT FOUND"

Here's the completed version of your code with clear explanations:

import java.util.Scanner;
public class Final1 {
    public static void main (String[] args) {
        int foundIndex = -1; // Start with -1 (signals no match initially)
        Scanner s = new Scanner(System.in);
        String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
        
        // Prompt user and read their input
        System.out.print("Enter String: ");
        String userInput = s.nextLine();
        
        // Loop through the array to check for a matching string
        for (int i = 0; i < names.length; i++) {
            // Use `equals()` to compare string content (never use == for this!)
            if (names[i].equals(userInput)) {
                foundIndex = i; // Store the index of the matching entry
                break; // Exit loop early once we find a match
            }
        }
        
        // Output the final result
        if (foundIndex != -1) {
            System.out.println("Found at index: " + foundIndex);
        } else {
            System.out.println("NOT FOUND");
        }
        
        s.close(); // Clean up the scanner to free system resources
    }
}

Key Details to Note:

  • foundIndex setup: We initialize this to -1 because array indices start at 0—this value acts as a flag that no match was found initially.
  • Reading input: s.nextLine() captures the entire string the user types (unlike next(), which stops at spaces).
  • String comparison: Using equals() is critical here. The == operator checks if two string objects are the same in memory, while equals() compares the actual text content—exactly what we need for this task.
  • Early loop exit: Once we find a match, we use break to stop looping, which saves unnecessary checks.
  • Scanner cleanup: Closing the Scanner object is good practice to avoid wasting system resources.

内容的提问来源于stack exchange,提问作者CaptainMuffenz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:33:54