Scanner throwing null pointer when trying to get next

null-self :
public class ScannerTest {

    protected Scanner scan;

    public ScannerTest(String s) {

        Scanner scan = new Scanner(s);

    }

    public void getone() {

        if (scan.hasNext()) {
            String temp = scan.next();
            temp = temp.replaceAll("[\\[\\](){}]", "");
            System.out.println(temp);
        }
    }

    public static void main(String[] args) {

        String s = "(abcd) (defg) (w)";
        ScannerTest test = new ScannerTest(s);
        Scanner rando = new Scanner(s);
        System.out.println(rando.next());
        System.out.println(rando.hasNext());

        test.getone();
    }
}
S. MS :

you are victim of so called variable shadowing. With line

Scanner scan = new Scanner(s); 

you are declaring a local variable scan instead of initialize your member scan inside a your ScannerTest class. Change the mentioned line to

scan = new Scanner(s); 

and it will work as desired...

complete source code

import java.util.Scanner;

public class SomeClass {

    protected Scanner scan;

    public SomeClass(String s) {
        scan = new Scanner(s);
    }

    public void getone() {

        if (scan.hasNext()){
            String temp = scan.next();
            temp = temp.replaceAll("[\\[\\](){}]","");
            System.out.println(temp);
        }

    }

    public static void main(String[] args) {

        String s = "(abcd) (defg) (w)";
        SomeClass test = new SomeClass(s);
        Scanner rando = new Scanner(s);
        System.out.println(rando.next());
        System.out.println(rando.hasNext());

        test.getone();

    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18641&siteId=1