Nikita Kovinskiy Nikita Kovinskiy - 1 year ago 61
Java Question

My variable is not initialized?

I have this method.

The error says

primeList might not have been initialized.

I can't understand how this can be true. I feel like there's no way the variable wouldn't be initialized out of the for loops.

I can't figure out how to initialize a String

public void primesToANumber(long num) //finds all primes
String primeList ;
long pcount;
long limit = num;
JOptionPane.showMessageDialog(null,"Prime numbers between 1 and " + limit);
for(long i = 1; i < 100; i++)
boolean isPrime = true;
for(long j = 2; j < i ; j++)
if(i % j == 0)
isPrime = false;
// print the number
primeList += i + ", ";
if(pcount % 12 ==0){
primeList += "\n";
JOptionPane.showMessageDialog(null, " " + primeList);

Answer Source

You need to initialise your variable, exactly like it says...

String primeList = "";

Using an empty string will then allow your code to append to it as you intend, to get your desired result.

Just for reference, if you did want to use null for some reason, you can 'convince' the compiler you know what you are doing by specifying it directly:

String primeList = null;

This would compile fine, but you would get a runtime error when you try to append to a null String, so it wouldn't make sense to do this in this instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download