Java 在函数中将 Scanner 对象作为参数传递的基本语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16599691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 12:22:30  来源:igfitidea点击:

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

javafunctionparametersargumentsjava.util.scanner

提问by hayonj

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 typeand argument nameas a parameter to the function... and simply call that function in the main using Scanner type and argumentas an argument to the function ?

这里似乎有什么问题?我早些时候让它工作了,我必须将Scanner 类型参数名称作为参数传递给函数......并简单地使用Scanner 类型和参数作为函数的参数在主函数中调用该函数?

-----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 !

@rgettman 谢谢!

采纳答案by rgettman

You need to pass the actual variable name inwhen you call the method, not the class name Scanner.

in调用方法时需要传递实际变量名,而不是类名Scanner

getChoice(in);

instead of

代替

getChoice(Scanner);

Incidentally, your getChoicemethod won't compile as shown. Just return what the scanner returns, which is an int, as you declared getChoiceto return an int:

顺便说一句,您的getChoice方法不会如图所示编译。只需返回扫描仪返回的内容,即int,正如您声明getChoice要返回的一样int

public static int getChoice(Scanner n){
    return n.nextInt();
}