Basic Syntax for passing a Scanner object as a Parameter in a Function

倾然丶 夕夏残阳落幕 提交于 2019-12-12 09:08:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!