【问题标题】:Java call nonvoid method for one value of manyJava为多个值中的一个调用非void方法
【发布时间】:2013-10-20 04:54:34
【问题描述】:

我有一个具有 4 个 int 值的 nonvoid 方法,但我只想“返回”其中一个 int 值。我在调用“calcpoints(final_points)”的语句中收到一条错误消息(如下)。

需要错误:int,int,int,int 发现:int 原因:实际参数列表和形式参数列表的长度不同

我的代码:

public static int calcpoints (int points, int total_points, int answer, int correct) {
  while ((points >= 0) && (answer != correct)) {
    System.out.println("Display problem");
    answer = GetInput.readLineInt();
    if (answer == correct) {
      total_points = total_points + points;
    } else { 
      points = points / 2;
    }
    total_points = total_points + points;
  }//end of while loop points
  return (total_points);
}//end of the calculate points method

【问题讨论】:

  • 你传递了多少个参数?
  • 你是怎么调用这个方法的?
  • 我在调用方法中有4个整数参数,但只需要传递一个,但我猜java不是这样工作的。我只想 System.out.print 一个参数,而不是全部 4 个。

标签: java methods call


【解决方案1】:

您的方法是用 4 整数参数定义的

public static int calcpoints (int points, int total_points, int answer, int correct)
{

}

但是在你的方法调用中,你只传递了1 参数,这是不对的。你需要传递4 整数参数

这是错误的:calcpoints(final_points)

这是对的(例如):calcpoints(1,2,3,4)

【讨论】:

  • 谢谢。我必须在 return 语句中编码所有参数吗?示例:返回 (1, 2, 3, 4)。我很挣扎,因为我只想在 system.out.println 语句中返回一个参数。
  • @user2899341:方法代码没有问题。顺便修复一下你没贴出来的方法调用。
  • 我的调用方法是 System.out.println("你的分数 --> " + calcpoints(total_points);
  • 通过返回是两个不同的东西。在向方法传递参数时,您需要遵守方法定义。如果您的方法定义定义了 4 个参数,则必须传递 4 个参数。就returning而言,只能返回scalar(single)值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多