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

Java生日提醒程序问题:为何无法进入第二个for循环及优化咨询

Fixing Your Birthday Reminder App & Optimization Tips

Hey Dillon, let’s get that birthday reminder app working properly and polished up—you’re right on the cusp of getting it done, so let’s break down what’s going wrong and how to fix it fast.

First: Why the Second Loop Isn’t Running

The biggest issue is your second for loop condition:

for(int j=0;j>0;j++)

When j starts at 0, j>0 is immediately false, so the loop never executes at all. That’s why your program stops before the query phase starts.

Other critical bugs in the original code:

  • You’re using == to compare strings (e.g., a[j]==names[k]). In Java, == checks if two objects are the same in memory, not if their text content matches. Always use equals() for string comparisons.
  • The query loop’s logic will print "Name not found" 9 times even if it finds a match (since it checks every index and outputs for each).
  • The else if(i==10) condition in the first loop will never trigger—your loop runs while i<10, so i will never reach 10.

Fixed Working Code

Here’s the corrected version that addresses all these issues:

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

public class BirthdayReminder {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] birthdays = new String[10];
        String[] names = new String[10];
        int count = 0; // Track how many valid entries we have

        // Input phase: collect names and birthdays
        for (int i = 0; i < 10; i++) {
            System.out.println("Enter name (or ZZZ to stop):");
            String name = input.nextLine().trim(); // Trim whitespace to avoid accidental matches
            
            if (name.equalsIgnoreCase("ZZZ")) { // Case-insensitive for better user experience
                break;
            }

            names[i] = name;
            System.out.println("Enter birthday for " + name + ":");
            birthdays[i] = input.nextLine().trim();
            count++; // Increment valid entry count
        }

        // Show all entered names
        System.out.println("\nEntered names:");
        for (int i = 0; i < count; i++) {
            System.out.println("- " + names[i]);
        }

        // Query phase: look up birthdays
        System.out.println("\nEnter a name to get their birthday (or ZZZ to exit):");
        while (true) {
            String queryName = input.nextLine().trim();
            
            if (queryName.equalsIgnoreCase("ZZZ")) {
                System.out.println("Exiting...");
                break;
            }

            boolean found = false;
            for (int i = 0; i < count; i++) {
                if (queryName.equals(names[i])) {
                    System.out.println(names[i] + "'s birthday is: " + birthdays[i]);
                    found = true;
                    break; // Exit loop once we find the match
                }
            }

            if (!found) {
                System.out.println("Name not found in the list.");
            }
        }

        input.close(); // Clean up the scanner
    }
}

Key Optimizations & Improvements

  • Use a while(true) loop for queries: It’s more intuitive than a for loop here, since we don’t know how many queries the user will make.
  • Track valid entries with count: Instead of looping through all 10 slots every time, we only check the actual entries the user added.
  • Case-insensitive exit trigger: Allowing zzz or Zzz to stop input makes the app more user-friendly.
  • Trim input whitespace: Prevents issues where the user accidentally adds spaces before/after a name.
  • Clean up the Scanner: Closing it is good practice to avoid resource leaks.
  • Better output formatting: Makes the app’s feedback clearer for the user.

Bonus: Even Better with HashMap

If you want to make the lookup faster (especially if you ever expand beyond 10 entries), using a HashMap instead of two arrays is a cleaner, more efficient approach:

import java.util.HashMap;
import java.util.Scanner;

public class BirthdayReminder {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        HashMap<String, String> birthdayMap = new HashMap<>();

        // Input phase
        while (birthdayMap.size() < 10) {
            System.out.println("Enter name (or ZZZ to stop):");
            String name = input.nextLine().trim();
            
            if (name.equalsIgnoreCase("ZZZ")) {
                break;
            }

            System.out.println("Enter birthday for " + name + ":");
            String birthday = input.nextLine().trim();
            birthdayMap.put(name, birthday);
        }

        // Show entered names
        System.out.println("\nEntered names:");
        for (String name : birthdayMap.keySet()) {
            System.out.println("- " + name);
        }

        // Query phase
        System.out.println("\nEnter a name to get their birthday (or ZZZ to exit):");
        while (true) {
            String queryName = input.nextLine().trim();
            
            if (queryName.equalsIgnoreCase("ZZZ")) {
                System.out.println("Exiting...");
                break;
            }

            if (birthdayMap.containsKey(queryName)) {
                System.out.println(queryName + "'s birthday is: " + birthdayMap.get(queryName));
            } else {
                System.out.println("Name not found in the list.");
            }
        }

        input.close();
    }
}

This version eliminates the need to track a count or loop through arrays—HashMap handles lookups in constant time, which is way more efficient.

You’ve got this—this should get your app working perfectly before that deadline!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:00:20