Error in java when creating Threads. The error is in “MainApp” with RandomCharacterThread being the error. The Thread t1 is expecting a char whereas i am giving it an int value. This is what had caused the error. I have added comments to make the code clearer for the community.
//Main class.
//program to display random numbers and characters using threads.
public class MainApp
{
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
Thread t1 = new Thread (new RandomCharacterThread("1"));
t1.start();
}
}
//RandomCharacterThread.
//Imports.
import java.util.Random;
//=====================================================================
public class RandomCharacterThread implements Runnable
{
//Variables.
char letter;
int repeats;
Random rand = new Random();
//Constructor
//=====================================================================
public void RandomCharacterThread(char x)
{
letter = x;
repeats = rand.nextInt(999);
}
public void run()
{
try
{
for(int i = 0;i < repeats; i++)
{
System.out.println("Character: " + letter);
}
}
catch(Exception e)
{
}
}
}
Your “constructor” takes a
charas an argument; you’re passing aString. You’d want to do something likeNote the single quotes rather than double quotes, which makes this a
charconstant rather than aStringwith one character.I say “constructor” in quotes because you actually don’t have one: you have a method that returns void with the same name as the class. Remove the “void” and you’ll be good. Constructors have no return type at all:
This is a very common newbie mistake, but most people only make it once!