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

Java菜单输入验证异常:输入1/2仍被判定为无效

输入验证始终判定无效的解决方法

需求

  • 实现包含2个选项的菜单,提示用户输入选项
  • 输入验证:若输入非“1”或“2”,输出错误信息并要求重新输入

原代码

import java.util.Scanner;
public class IndenteurPseudocode {

    public static void main(String[] args) {


        System.out.println("Ce programme permet de corriger l'indentation d'un algorithme ecrit en pseudocode.\n");
        System.out.println("----");
        System.out.println("Menu");
        System.out.println("----");
        System.out.println("1. Indenter pseudocode");
        System.out.println("2. Quitter\n");
        
        Scanner myObj = new Scanner(System.in);
        String choixMenu;
        boolean valid = false;

        while(!valid) {
            System.out.print("Entrez votre choix : ");
            choixMenu = myObj.nextLine();
            if ( choixMenu == "1" || choixMenu == "2") {
                valid = true;
                System.out.print(choixMenu);
            } else {
                System.out.println("invalid");
            }
        }
        
    }

}

运行异常

Ce programme permet de corriger l'indentation d'un algorithme ecrit en pseudocode.

----
Menu
----
1. Indenter pseudocode
2. Quitter

Entrez votre choix : 1
invalid
Entrez votre choix : 2
invalid
Entrez votre choix : 3
invalid
Entrez votre choix : 

问题根源

Java中字符串比较不能用==运算符,==比较的是两个字符串对象的内存引用地址,而非字符串的实际内容。用户输入的字符串和字面量"1"、"2"是不同的对象,因此==永远返回false,导致所有输入都被判定无效。

修正后的代码

import java.util.Scanner;
public class IndenteurPseudocode {

    public static void main(String[] args) {


        System.out.println("Ce programme permet de corriger l'indentation d'un algorithme ecrit en pseudocode.\n");
        System.out.println("----");
        System.out.println("Menu");
        System.out.println("----");
        System.out.println("1. Indenter pseudocode");
        System.out.println("2. Quitter\n");
        
        Scanner myObj = new Scanner(System.in);
        String choixMenu;
        boolean valid = false;

        while(!valid) {
            System.out.print("Entrez votre choix : ");
            choixMenu = myObj.nextLine();
            // 改用equals()方法比较字符串实际内容
            if ("1".equals(choixMenu) || "2".equals(choixMenu)) {
                valid = true;
                System.out.print(choixMenu);
            } else {
                System.out.println("invalid");
            }
        }
        
    }

}

补充说明

把字面量放在equals()前面(如"1".equals(choixMenu))可以避免NullPointerException——当用户输入为空字符串或choixMenu意外为null时,不会抛出空指针异常,而是直接返回false,代码更健壮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:11:30