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

Java新手调用私有方法报参数不匹配错误该如何解决?

问题解答

核心报错原因

  • 你定义的printDice(int num_random, int num_random2)方法要求传入2个int类型参数,printSpecialMessage(int total)要求传入1个int类型参数,但是你在main方法中调用这两个方法时没有传入任何参数,因此触发参数不匹配的报错。
  • 你调用rollDie()和rollDie2()生成的随机数有返回值,但是没有用变量接收,结果直接丢失,也无法传递给后续方法使用。

其他需修复的代码问题

  • printDice方法内使用的total变量没有提前声明,需要先声明int total再进行赋值运算
  • printSpecialMessage方法的条件判断用错了符号:=是赋值运算符,判断两个值相等需要用==
  • printSpecialMessage的else分支中使用break是非法的,break只能在循环或者switch结构中使用,普通代码块不需要写break,直接删掉即可
  • 类中定义的int total = num_random + num_random2;是无效代码,类成员变量不能直接引用其他方法内的局部变量,直接删掉这段即可

修正后可正常运行的代码

import java.util.Scanner;

public class project2 {
    
    private static int rollDie() {
        int num_random2 = (int) (Math.random() * 6) + 1;
        System.out.println("Die 2: " + num_random2);
        return num_random2;
    }
    
    private static int rollDie2() {
        int num_random = (int) (Math.random() * 6) + 1;
        System.out.println("Die 1: " + num_random);
        return num_random;
    }

    private static int printDice(int num_random, int num_random2) {
        int total = num_random + num_random2;
        System.out.println("Total: " + total);
        return total;
    }

    private static void printSpecialMessage(int total) {
        String message1 = "Snake Eyes";
        String message2 = "Box cars";
        if (total == 12) {
            System.out.println(message2);
        } else if (total == 2) {
            System.out.println(message1);
        }
    }

    public static void main(String[] args) {
        System.out.println("Welcome to my app!");
        System.out.println();
        System.out.println("Dice Roller");
        System.out.println();

        Scanner sc = new Scanner(System.in);

        String choice = "y";

        do {
            int die1Val = rollDie2();
            int die2Val = rollDie();
            int total = printDice(die1Val, die2Val);
            printSpecialMessage(total);

            System.out.print("Roll Again? (y/n): ");
            choice = sc.next();
            System.out.println();
            
        }
        while (choice.equalsIgnoreCase("y"));
        sc.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:39:04