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

Java if else程序if条件为false时else语句未正常输出问题

问题根因

  • System.in.read() 用于读取输入流中的单个字符,返回的是该字符对应的ASCII码整数值,而非你输入的数字本身。
  • 你输入12时,方法仅读取第一个字符'1',对应的ASCII码为49,49 >= 18判断成立,因此不会执行else分支的打印逻辑。

修复代码

使用Scanner类读取整数输入即可解决问题,修正后的代码如下:

import java.util.Scanner;

public class rtr { 
    public static void main(String args[]) {
        int age;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age: "); 
        age = sc.nextInt(); 
        if(age >= 18) {
            System.out.println("You are eligible for voting"); 
        } else {
            System.out.println("You are not eligible for voting");
        }
        sc.close();
    }
}

补充说明:原代码中单词elligible为拼写错误,正确拼写为eligible。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 17:33:01