问题
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 ?
-----EDIT-----
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 Thanks !
回答1:
You need to pass the actual variable name in
when you call the method, not the class name Scanner
.
getChoice(in);
instead of
getChoice(Scanner);
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();
}
来源:https://stackoverflow.com/questions/16599691/basic-syntax-for-passing-a-scanner-object-as-a-parameter-in-a-function