如何判断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
namesarray - 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:
foundIndexsetup: We initialize this to-1because 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 (unlikenext(), which stops at spaces). - String comparison: Using
equals()is critical here. The==operator checks if two string objects are the same in memory, whileequals()compares the actual text content—exactly what we need for this task. - Early loop exit: Once we find a match, we use
breakto stop looping, which saves unnecessary checks. - Scanner cleanup: Closing the
Scannerobject is good practice to avoid wasting system resources.
内容的提问来源于stack exchange,提问作者CaptainMuffenz
相关产品推荐
相关产品推荐

