方法不能应用于给定的类型 [英] method cannot be applied to given types

查看:209
本文介绍了方法不能应用于给定的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我试图在另一个类中调用throwDice方法.

In my program, I'm trying to call the throwDice method in a different class.

public class SimpleDice {  
  private int diceCount;

  public SimpleDice(int the_diceCount){
    diceCount = the_diceCount;
  }

  public int tossDie(){
    return (1 + (int)(Math.random()*6));
  }

  public int throwDice(int diceCount){
           int score = 0;
           for(int j = 0; j <= diceCount; j++){
            score = (score + tossDie());
           }
           return score; 
         }
}

import java.util.*; 

public class DiceTester {
public static void main(String[] args){

  int diceCount;
  int diceScore;

    SimpleDice d = new SimpleDice(diceCount);

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter number of dice.");
    diceCount = scan.nextInt();
    System.out.println("Enter target value.");
    diceScore = scan.nextInt();

    int scoreCount = 0;

    for(int i = 0; i < 100000; i++){
     d.throwDice();
      if(d.throwDice() == diceScore){
        scoreCount += 1;
      }
    }
    System.out.println("Your result is: " + (scoreCount/100000));
}
}

当我编译它时,d.throwdice()会弹出一个错误,提示无法应用.它说它需要一个int,没有参数.但是我在throwDice方法中调用了一个int diceCount,所以我不知道出了什么问题.

When I compile it, an error pops up for the d.throwdice() and says it can't be applied. It says it needs an int and there are no arguments. But I called an int diceCount in the throwDice method, so I don't know what's wrong.

推荐答案

for(int i = 0; i < 100000; i++){
 d.throwDice();
  if(d.throwDice() == diceScore){
    scoreCount += 1;
  }
}

此代码有两点错误:

  1. 它调用不带intthrowDice(您已将其定义为public int throwDice(int diceCount),因此必须给它一个int)
  2. 每个循环调用throwDice两次
  1. It calls throwDice without an int (you have defined it as public int throwDice(int diceCount), so you must give it an int)
  2. It calls throwDice twice each loop

您可以这样解决它:

for(int i = 0; i < 100000; i++){
 int diceResult = d.throwDice(diceCount); // call it with your "diceCount"
                                          // variable
  if(diceResult == diceScore){ // don't call "throwDice()" again here
    scoreCount += 1;
  }
}

这篇关于方法不能应用于给定的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆