这是我写的非常基本的内容:
import java.util.Scanner;
public class Projet {
/**
* @param args
* @param Scanner
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter a digit");
Scanner in = new Scanner(System.in);
getChoice(Scanner);
in.close();
}
public static int getChoice(Scanner n){
n = in.nextInt();
return n;
}
}
这里似乎出了什么问题?我之前已经让它工作了,我必须将扫描仪类型和参数名称作为参数传递给函数......然后简单地使用在主函数中调用该函数>扫描仪类型和参数作为函数的参数?
-----编辑-----
下面需要它的新代码:
import java.util.Scanner;
public class Projet {
/**
* @param args
* @param Scanner
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter a digit");
Scanner in = new Scanner(System.in);
System.out.println(getChoice(in));
in.close();
}
public static int getChoice(Scanner in){
return in.nextInt();
}
}
@rgettman 谢谢!
最佳答案
调用该方法时,需要传递实际的变量名in
,而不是类名Scanner
。
getChoice(in);
而不是
getChoice(Scanner);
顺便说一句,您的 getChoice
方法将不会如图所示进行编译。只需返回扫描仪返回的内容,即 int
,正如您声明 getChoice
返回 int
一样:
public static int getChoice(Scanner n){
return n.nextInt();
}
关于java - 将 Scanner 对象作为函数中的参数传递的基本语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16599691/