Print the contents of an array at even intervals

I have a program that introduces the user and prints that many palindromic primes (10 per line and should be evenly distributed). I printed the values ​​directly and it worked fine, but the numbers are not evenly distributed. So I decided to store them in an array in the hope that they would print evenly. But now the values ​​are not printed. Can someone point out where I made a mistake? Here is the piece of 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] + " ");
        }
    }
+4
source share
2 answers

You need to increase countwhen adding val, or your cycle will never end.

if (isPrime(val) && isPalindrome(val)) 
{
    palPrimes[count - 1] = val;
}
val++;

It should be something like

if (isPrime(val) && isPalindrome(val)) 
{
    palPrimes[count - 1] = val;
    count++;
}
val++;

, formatting. - ,

for (int i = 0; i < palPrimes.length; i++) {
    if (i % 10 == 0)
        System.out.println();
    System.out.printf("% 5d", palPrimes[i]);
}

, @m3ssym4rv1n,

System.out.print(palPrimes[i] + "\t");

(printf) ; (\t) .

+3

count++ while. , :

System.out.printf("%-5d", palPrimes[i]);

"-5d" 5

0

Source: https://habr.com/ru/post/1607746/


All Articles