在函数中将Scanner对象作为参数传递的基本语法 [英] Basic Syntax for passing a Scanner object as a Parameter in a Function
问题描述
这是我写的非常基本的内容:
Here is what I wrote which is pretty basic :
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;
}
}
这里似乎有什么问题?我早先使用过它,我必须将扫描仪类型和自变量名称作为参数传递给该函数...并只需使用扫描仪类型和参数作为函数的参数?
What seems to be wrong here ? I had it working earlier, I had to pass the Scanner type and argument name as a parameter to the function... and simply call that function in the main using Scanner type and argument as an argument to the function ?
-----编辑-----
下面的下面的新代码将需要它:
New Code below for below that will need it :
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谢谢!
@rgettman Thanks !
推荐答案
调用方法时,您需要传递实际的变量名in
,而不是类名Scanner
.
You need to pass the actual variable name in
when you call the method, not the class name Scanner
.
getChoice(in);
代替
getChoice(Scanner);
偶然地,您的getChoice
方法将无法如图所示进行编译.只需返回扫描程序返回的内容,即int
,就像您声明getChoice
来返回int
:
Incidentally, your getChoice
method won't compile as shown. Just return what the scanner returns, which is an int
, as you declared getChoice
to return an int
:
public static int getChoice(Scanner n){
return n.nextInt();
}
这篇关于在函数中将Scanner对象作为参数传递的基本语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!