Make a Static method in the main class that writes on the screen all even numbers from 1 to 10000 that are palindromes

Asked

Viewed 400 times

0

This is my method:

public static void B()
{
    int vet[]=new int [100];
    int vet2[]=new int [vet.length/2];
    for(int i=0;i<=vet.length;i++)

    {
        vet[i]=i+1;
    }
    for(int i=0;i<vet.length;i++)
    {
        int rest = vet[i]%2;
        if(rest==0)
        {
            vet2[i]=vet[i];
        }
    }
    for (int i = 0; i <= vet2.length; i++) 
    {
        if(vet2[i]==(vet2[i-1])-i)
        {
            System.out.println(vet2[i]+"É PALINDROMO");
        }
    }

And this is the error that appears:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
  at lista1.pkg05.Lista105.B(Lista105.java:59)
  at lista1.pkg05.Lista105.main(Lista105.java:15)
C:\Users\Pichau\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:

Java returned: 1

  • This code has some errors, but we need to know its goal to fix, especially in the last loop that certainly makes account wrong. If you are going to find out if a array is the inverse of the other, it is obvious that in this algorithm is not.

  • Hello Fernando, could you please explain what you want? Either only the code correction or actually the algorithm to check if the number is palindromic?

3 answers

4


The algorithm has an error in for because it reads one more number. You cannot buy with <= to size because the count starts at 0, it has to be with <. It would also work to use this comparison by subtracting 1, but this generates a larger computational effort and it makes no sense to use it like this.

The access to check if it is palindromic has a wrong formula and causes problem as well. I improved, but I think it’s still not what you want, because it’s to check if the array is palindromic and does not say about each element, but will know.

One of the arrays has no function in the algorithm other than complicate.

By this algorithm will never be palindromic, but I hope it will generate the array with some other algorithm. Would it be to check if the digits of each number is palindromic? Then the algorithm is another. But you’re already in trouble.

I only kept the first 100 as asked in the question, maybe to make it easier to test, to go up to 10000, just change the size of the array.

I gave one organized in the code too.

class HelloWorld {
    public static void main (String[] args) {
        int vet[] = new int[50];
        for (int i = 0; i < vet.length; i++) if (i % 2 == 0) vet[i] = (i + 1) * 2;
        for (int i = 0; i < vet.length; i++) if (vet[i] == vet[vet.length - i - 1]) System.out.println(vet[i] + " É PALINDROMO");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference. Data is missing, but at least the error disappears.

  • I don’t know if it makes sense to publish such careful code, replicate in multiple places, and that it generates an output that makes no sense at all. The purpose of the A.P. is very clear in the question’s title: it wants to print the numbers that are Palindromes. I think a cool approach would be to correct the limits of for and other mistakes - but then question this chosen approach, which will lead nowhere. (Yes, I saw that you said that this can detect if the "array is a palindrome" - but that’s not the goal - it’s in the title)

  • What is in the title is not even in the scope of the site. We are here to solve specific problems not perform entire algorithms for the person. It seems to me that acceptance indicates that it solved what he wanted. I like my workflow this way and prefer to maintain a pattern.

2

Well, I’ll approach it in a more legible way.

public class HelloWorld {
   public static void main(String[] args) {
      Palindromas();
   }
   public static void Palindromas()
   {

       StringBuilder sb = new StringBuilder();//Alocar Espaço para um SB

       for(int i = 1; i <= 10000; i++) {

         sb.append(i);//Adicionar o número no sb

         sb.reverse();//Inverter o número

         if(
            i % 2 == 0 // se  é par
            && // E
            Integer.parseInt(sb.toString()) == i //Ele ao contrário é igual a ele normal
            ){
             System.out.println(i);//Printa
         }

         sb.setLength(0);//Limpa o Buffer pra reutiliza-lo no proximo item do loop

      };
   }
}

I only did so because I already had more answers, mine is a workaround ;)

  • In fact, the other answers point to the error of the author’s code, but do not print the numbers that are palindromes.

1

The problem is in these two lines;

for(int i=0;i<=vet.length;i++)

for (int i = 0; i <= vet2.length; i++) 

The length property returns the total size of elements in the array, so when using to iterate an array like the code above, in an array of 10 positions it will run 11 times from 0 to 10 thus giving the Arrayindexoutofboundsexception error in the first iteration, to solve the problem follow the code below.

for(int i=0;i<=vet.length -1;i++)

for (int i = 0; i <= vet2.length -1; i++) 

Done so the code will go through 10 times from 0 to 9.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.