运行 Java 代码时出现一些错误。它编译得很好,但我得到运行时错误和异常。这是代码:
import java.io.*;
class display {
private int charNumber;
private char[] currentArray;
public display() {
charNumber = 0;
}
public void dispText(String text, long speed, long wait) {
while(currentArray[charNumber] != '~') {
currentArray = text.toCharArray();
System.out.print(currentArray[charNumber]);
try {
Thread.sleep(speed);
} catch (NullPointerException e) {
System.out.println("Error in the Thread process:\n" + e);
} catch (InterruptedException e) {
System.out.println("Error in the Thread process:\n" + e);
}
charNumber++;
}
charNumber = 0;
try {
Thread.sleep(wait);
} catch (NullPointerException e) {
System.out.println("Error in the Thread process:\n" + e);
} catch (InterruptedException e) {
System.out.println("Error in the Thread process:\n" + e);
}
}
public void resetCharNumber() {
charNumber = 0;
}
}
class Main {
public static void main (String[] args) throws Exception {
//Make sure to include a '~' at the end of every String.
String start = "Hey, is this thing on?~";
String hello = "Hello, World!~";
display d = new display();
d.dispText(start, 200, 2000);
d.dispText(hello, 200, 2000);
System.out.println("\nDone!");
}
}
void dispText
需要一个字符串来显示文本,System.out.print
长速度来确定每次显示一个字符时经过多少时间(如打字机)和长等待,以确定在执行下一个过程之前经过了多少时间。dispText
获取 String 文本,将其转换为 char 数组text.toCharArray();
,然后进入 while 循环,每次运行显示一个字符,然后等待 speed 指定的时间,然后移动到下一个字符。它会一直这样做,直到它到达最后一个字符('~'),该字符作为最后一个字符包含在提供给文本的字符串中。然后,它移动到下一行。然后在main中,创建了一个显示类的实例,命名为'd',并且d执行了两次dispText。
这是我运行它时遇到的运行时错误:
运行时错误:在 Main.main(Main.java:48)
的 display.dispText(Main.java:14)处的线程“main”java.lang.NullPointerException中的异常