gpt4 book ai didi

java - 扫描仪在尝试获取下一个时抛出空指针

转载 作者:行者123 更新时间:2023-12-02 01:02:39 26 4
gpt4 key购买 nike

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();
}
}

最佳答案

你是所谓的变量阴影的受害者。带线

Scanner scan = new Scanner(s); 

您正在声明一个局部变量 scan,而不是在 ScannerTest 类中初始化您的成员 scan。将提到的行更改为

scan = new Scanner(s); 

它将按预期工作...

完整的源代码

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();

}

}

关于java - 扫描仪在尝试获取下一个时抛出空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469205/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com