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

Java实现除法与取余并输出等式时的语法错误解决方法

Java除法与取余运算代码的语法错误修复

你的代码核心错误出在System.out.println的输出语句上——你错误地在输出里使用了赋值语法,Java不允许将算术表达式(如integerOne/integerTwo)放在等号左侧,这直接导致了语法错误。正确的做法是通过字符串拼接,把数字、运算符、计算结果组合成符合要求的输出格式。

另外还有个小问题:变量名modolus拼写错误,正确的单词是modulus,虽然不影响代码运行,但建议修正以保持命名规范。

修正后的完整代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int integerOne;
        int integerTwo;  
        int division;
        int modulus;
        int divisionTwo;
        int modulusTwo;
        Scanner input = new Scanner(System.in);

        System.out.print("Enter an integer: ");
        integerOne = input.nextInt();
        
        System.out.print("Enter another integer: ");
        integerTwo = input.nextInt();
        
        input.close();
        
        // 先完成运算计算
        division = integerOne / integerTwo;
        modulus = integerOne % integerTwo;
        divisionTwo = integerTwo / integerOne;
        modulusTwo = integerTwo % integerOne;
        
        // 通过字符串拼接输出目标等式格式
        System.out.println(integerOne + "/" + integerTwo + " = " + division);
        System.out.println(integerOne + "%" + integerTwo + " = " + modulus);
        System.out.println(integerTwo + "/" + integerOne + " = " + divisionTwo);
        System.out.println(integerTwo + "%" + integerOne + " = " + modulusTwo);
    }
}

额外健壮性提示

运行代码时如果输入的整数为0,会触发ArithmeticException(除以零异常)。如果需要让代码更稳定,可以在计算前增加判断逻辑:

if (integerTwo == 0 || integerOne == 0) {
    System.out.println("输入的整数不能为0");
    return;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:40:20