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

Java主方法变量复用:如何实现条件触发的指定代码段重执行?

Fixing the "Retry Invalid Input" Logic in Your OddsAndEvens Game

No worries, this is a super common scenario—you just need to add a loop to retry the input when it's invalid, and optionally refactor the logic to keep your main method clean. Let's walk through two straightforward solutions.

Solution 1: Use a do-while Loop Directly in main

This is the simplest fix if you want to keep most code in main. We'll wrap the preference selection logic in a loop that runs until the user enters a valid choice:

import java.util.*;
public class OddsAndEvens {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Let's play a game called Odds And Evens");
        System.out.println();
        System.out.println("What is your name? ");
        String name = input.nextLine();
        
        String pref = "";
        // Wrap the preference selection in a do-while loop
        do {
            System.out.println("Hi " + name + "! Which do you choose? Odds or Evens?");
            pref = input.nextLine().trim(); // Trim whitespace to handle accidental spaces
            
            if (pref.equalsIgnoreCase("Odds")) {
                System.out.println(name + " has picked odds! Computer will be evens");
                break; // Exit loop since input is valid
            } else if(pref.equalsIgnoreCase("Evens")) {
                System.out.println(name + " has picked evens! Computer will be odds");
                break; // Exit loop since input is valid
            } else {
                System.out.println("Please enter a valid answer (Odds or Evens)");
            }
        } while (true); // Loop forever until valid input is received
        
        // Rest of your game logic goes here
    }
}

Key details:

  • We use equalsIgnoreCase() to avoid checking both "Odds" and "odds" separately—it's way cleaner!
  • The do-while loop ensures the prompt runs at least once, then keeps repeating until the user enters a valid choice.
  • trim() removes any accidental leading/trailing spaces from the input, so typos like " Odds " don't count as invalid.

Solution 2: Extract the Preference Logic to a Separate Method

If you want to keep your main method tidy (a great practice for larger programs), you can move the input validation into its own helper method. This way, main just calls the method to get a guaranteed valid preference:

import java.util.*;
public class OddsAndEvens {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Let's play a game called Odds And Evens");
        System.out.println();
        System.out.println("What is your name? ");
        String name = input.nextLine();
        
        // Call our helper method to get a valid preference
        String pref = getUserPreference(input, name);
        
        // Use the valid preference for the rest of the game
        if (pref.equalsIgnoreCase("Odds")) {
            System.out.println(name + " has picked odds! Computer will be evens");
        } else {
            System.out.println(name + " has picked evens! Computer will be odds");
        }
        
        // Rest of your game logic goes here
    }
    
    // Helper method to handle all input validation
    private static String getUserPreference(Scanner input, String userName) {
        String pref;
        do {
            System.out.println("Hi " + userName + "! Which do you choose? Odds or Evens?");
            pref = input.nextLine().trim();
            
            if (!pref.equalsIgnoreCase("Odds") && !pref.equalsIgnoreCase("Evens")) {
                System.out.println("Please enter a valid answer (Odds or Evens)");
            }
        } while (!pref.equalsIgnoreCase("Odds") && !pref.equalsIgnoreCase("Evens"));
        
        return pref;
    }
}

Key details:

  • The getUserPreference method takes the existing Scanner and user's name as parameters (no need to create a new Scanner instance!).
  • It handles all the looping and validation logic, then returns a valid preference to main.
  • This makes main much shorter and focused on the game's high-level flow, which is easier to maintain as your game grows.

Either approach will solve your problem—pick the one that feels more readable and fits your coding style!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:11:02