在函数中将 Scanner 对象作为参数传递的基本语法 [英] Basic Syntax for passing a Scanner object as a Parameter in a Function

查看:29
本文介绍了在函数中将 Scanner 对象作为参数传递的基本语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我写的非常基本的内容:

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 ?

-----编辑-----

下面需要它的新代码:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆