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

如何解决Eclipse IDE中if-else语句始终输出错误结果的问题?

问题分析与解决

核心问题

你的代码里的if判断条件直接写死成了false,这导致该分支永远不会被触发,不管用户输入什么内容,程序都会执行else分支,所以始终显示"Your answer is Wrong"。

正确逻辑与修改方案

题目问的是"Can an identifier have spaces?"(标识符能否包含空格),Java中标识符不允许包含空格,所以正确答案是False。你需要把if条件改成判断用户输入的答案是否匹配正确值,同时建议忽略大小写,避免因为用户输入小写false或混合大小写导致判断错误。

修改后的代码如下:

import java.util.Scanner;

public class ICTPETA {

    public static void main(String[] args) {
        
        Scanner input = new Scanner (System.in);
        
        System.out.print("Name: ");
        String name = input.nextLine();
        
        System.out.print("Date: ");
        String date = input.nextLine();
        
        System.out.println ("A. True or False");
        System.out.println ("Directions: Read each statement carefully. If the statement is correct, type True. Otherwise, type False");
        
        String answer1 = "";
        
        System.out.println ("1. Can an identifier have spaces?");
        answer1 = input.nextLine();
        
        // 修改判断条件,忽略大小写比较正确答案
        if (answer1.equalsIgnoreCase("False"))
        {
            System.out.println("Your answer is Correct!");
        }
        
        else
        {
            System.out.println("Your answer is Wrong");
        }
        
        input.close(); // 释放Scanner资源
    }
}

额外说明

  • 使用equalsIgnoreCase()方法可以忽略用户输入的大小写,比如用户输入false、FALSE都能被判定为正确。
  • 调用input.close()是良好的编程习惯,能及时释放Scanner占用的系统资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 22:21:35