scanner.next()和String之间的类型错误不兼容

时间:2017-01-17 23:38:49

标签: java string java.util.scanner incompatibletypeerror

我正在尝试编译这段代码,它告诉我,while循环中的in.next()String不兼容,但我认为next()方法返回一个String

我有Scanner类和java.io

的导入语句
public static void main ( String[] args){
    Scanner in = new Scanner(new File(args[0]));
    while ( in.hasNext()){
        in = stringReverse(in.next());
    }
}

public static String stringReverse ( String s ) {...}

2 个答案:

答案 0 :(得分:0)

in = stringReverse(in.next());

Scanner#next()返回一个String,传递给stringReverse(),返回一个String。您尝试将该字符串保存在in中,该字符串指向Scanner对象。

答案 1 :(得分:0)

分配String类型的错误参考。 请参阅下面的正确代码。希望这有帮助

    public static void main ( String[] args){
        Scanner in = new Scanner(new File(args[0]));
        String assignStringHere = "";
        while ( in.hasNext()){
            assigneStringHere = stringReverse(in.next());
        //in ----> is not an object of String class, rather its an object of Scanner class 
        //Thats the reason you are getitng the erro.
        }
    }