【问题标题】:Parameter Scanner [closed]参数扫描仪[关闭]
【发布时间】:2013-05-15 20:09:31
【问题描述】:

这是我的问题:

我有一个方法,其中一个参数是 Scanner cons,如下所示:

public void buyIngredients (Scanner cons){}

它有效,但主要是错误:

import java.util.Scanner;
public class Main{

public static void main(String [] args){
Hero h = new Hero();
Scanner scan = new Scanner(System.in);
int value = scan.nextInt();
System.out.println(h.buyIngredients(value));

错误是这样的:

Main.java:11: error: method buyIngredients in class Hero cannot be applied to given types;
System.out.println(h.buyIngredients(value)); 
                    ^
 required: Scanner
 found: int
 reason: actual argument int cannot be converted to Scanner by method invocation conversion

【问题讨论】:

  • 该错误准确地说明了问题所在。它需要Scanner,而您提供的是int。请阅读错误文本。

标签: java methods parameters java.util.scanner


【解决方案1】:

您的方法buyIngredients 采用Scanner,但您传递了int,这是不正确的。改为传递Scanner

System.out.println(h.buyIngredients(scan));

【讨论】:

  • 我用扫描试试,现在的错误是:这里不允许'void'类型 System.out.println(h.CompraIngredientes(scan));并标记扫描
  • @Fletcher 您的问题是您试图将错误的变量类型传递给这些函数。无论您在() 中为函数定义什么,都是代码所期望的对象类型。如果您提供不同的类型,该函数将不知道该做什么,并抛出您看到的这些错误。
  • 你的方法buyIngredients 没有返回任何东西;方法签名说void。你想打印什么?
  • @rgettman 是的,它是无效的并且不返回任何内容,我尝试打印一个菜单,只是调用该方法
  • @Fletcher,在System.out.println 之外致电h.buyIngredients(scan)。您上面的评论是“菜单”的第一次出现。不知道那是什么,您的代码可能看起来像这样:System.out.println(h.getMenu());.
【解决方案2】:

您的buyIngredients (Scanner cons) 接受Scanner 对象。在您的代码中,您传入value,这是一个int。您不能将 int 类型强制转换为特定对象。

【讨论】:

  • 我认为 a 必须更具体,但我该如何解决?
  • 传入Scanner 对象。您在错误之前创建了两行! Scanner scan = new Scanner(System.in);
  • @Leigh 即使传递了Scanner,该函数也会返回void。这只是一堆问题都粘在一起。
  • @Walls - 非常正确。我只是从第一个错误开始,即一次修复一个错误,然后从那里开始;-)
【解决方案3】:

您的 buyIngredients(Scanner cons) 方法需要一个 Scanner 作为参数。我怀疑应该改成buyIngredients(int cons),但是除非我能看到方法体,否则我无法知道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 2014-06-29
    • 1970-01-01
    • 2023-04-05
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多