I have a program that takes user input and prints that many palindromic primes (10 per line only and should be evenly spaced). I was printing the values directly and it was working fine, but the numbers are not evenly spaced. So I decided to store them into an array in hopes that they would print out evenly spaced. But now no values are printing. Can someone please point out where I made a mistake? Here is part of the code:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Print how many values? ");
int input = scan.nextInt();
int[] palPrimes = new int[input];
int count = 1, val = 2;
while(count <= input)
{
if(isPrime(val) && isPalindrome(val))
{
palPrimes[count-1] = val;
}
val++;
}
for(int i = 0; i < palPrimes.length; i++)
{
if(i % 10 == 0)
System.out.println();
System.out.print(palPrimes[i] + " ");
}
}
You need to increment count
when you add a val
or your loop never terminates.
if (isPrime(val) && isPalindrome(val))
{
palPrimes[count - 1] = val;
}
val++;
Should be something like
if (isPrime(val) && isPalindrome(val))
{
palPrimes[count - 1] = val;
count++;
}
val++;
Finally, for even spacing of the numbers, I suggest you use formatting. Something like,
for (int i = 0; i < palPrimes.length; i++) {
if (i % 10 == 0)
System.out.println();
System.out.printf("% 5d", palPrimes[i]);
}
Or, as pointed out in the comments by @m3ssym4rv1n, a tab or two
System.out.print(palPrimes[i] + "\t");
The first option (printf
) will align right; the later (\t
) aligns left.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With