I get some errors when I run my Java code. It compiles fine, but I get runtime errors with exceptions. This is the code:
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!");
}
}
The void dispText takes a string to display text with System.out.print, the long speed to determine how much time passes every time a character is displayed (like a typewriter) and the long wait, to determine how much time passes before the next process is executed. dispText takes the String text, converts it to a char array with text.toCharArray();, and then goes into a while loop where it displays one character per run, then waits the time designated by speed, and then moves on to the next character. It does so until it reaches the last character (‘~’) which is included as the last character in the Strings that are fed to text. Then, it moves on to the next line. Then in main, an istance of the display class is created, named ‘d’, and d executes dispText twice.
This is the runtime error I get when I run it:
Runtime error: Exception in thread “main” java.lang.NullPointerException
at display.dispText(Main.java:14)
at Main.main(Main.java:48)
You declared your array like: –
But you never initialized it. You should initialize it in constructor like: –
OR, as noted in the comment, you are rather initializing the array, but at wrong location.
You have this code in your while loop: –
just move the first statement outside the while loop: –
And then you won’t need to initialize the array in constructor.
As a side note, please follow Java Naming Conventions. Class name should start with Uppercase letters and should follow CamelCasing thereafter.