Why is the code not running the for loop, even though the compiler is not showing an error?

Asked

Viewed 177 times

1

I was doing an exercise on vectors, where the goal was to build a program that received a number n for input that would define the size of the vector, and then receive, also by input, others n numbers to be allocated in this vector.

Thereafter a method should be used to find the largest number among the latter. But the problem I found is precisely in the way I found to take and allocate these n numbers on my vector.

After testing my program several times I saw that the method is called, but the loop for, that was before nor is started. I really do not know what can be.

Print de quando rodei o programa; aparentemente o laço for não é executado

The code:

import java.util.Scanner;
//bubble sort array
public class EP6_1 {

    public static int maiorNumero(int array[]) {
        int resposta;
        for (int x = 0; x == array.length - 1; x++) {
            if (array[x] >= array[x+1]) {
                for ( int c = 0; c == array.length - 1; c++ ) { //c é o contador
                    int temp = array[c];
                    array[c] = array[c+1];
                    array[c+1] = temp;
                }
            }
        }
        resposta = array[array.length-1]; 
        return resposta ;
    }

    public static void main(String[] args) {

        Scanner leitor = new Scanner(System.in);

        int lista[];

        System.out.println("Digite o tamanho do vetor"); //numero de elementos
        int N = leitor.nextInt();                        //da lista

        lista = new int[N];

        for (int i = 0; i == N - 1; i++) { //i é o contador
            System.out.println("teste");
            lista[i] = leitor.nextInt();
        }
        System.out.println(">>>>>>>");
        System.out.println(maiorNumero(lista));

    }

}
  • 2

    Provide the code in textual form always, so that it is possible not only to view, but also to execute.

  • 3

    Before you see the code, and it’s hard to see how your IDE looks (why don’t you glue the code here and make it easy for us?) you get the wrong idea of what a compiler is, and maybe what a program is. It doesn’t show because there is no error that the compiler can detect and that prevents the compilation, but it has one of the infinite errors that a code can have, and it’s part of the programmer’s job to find when the co-conspirator can’t find it for you. With the code I can see if I can say anything else.

  • 1

    Sorry, this is my first post. I just edited and put the code, but I believe that also not got the desired formatting

  • Code formatting tips: https://answall.com/editing-help#code

  • No matter where it’s written i == N - 1 swap for i <= N - 1

  • 1

    Making an analogy - well simplistic - the compiler is like a "spell checker". You can write a text without grammatical errors - which the broker considers correct - but which only says nonsense (and this the broker does not detect). Just as you can write code without compilation errors (and therefore the compiler does not complain), but with wrong logic (does not do what should).

  • @Bruno_smr Did any of the answers solve your question? Do you think you can accept one of them? See [tour] how to do this, if you haven’t already done so. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (you will get enough score right after you accept an answer).

Show 2 more comments

2 answers

7

The condition of for is i == N - 1, so the loop will perform whenever this condition is true. It does not need to perform if the face condition is already false. Just before you said i is equal to 0, therefore the condition will only be true if the N for 1 (basic mathematical logic), in no other situation is this true, so any number that is typed and placed in N that is not 1 the condition will be false and the tie will not perform even once.

Probably what I wanted to do was something like this:

for (int i = 0; i < N; i++)

I put in the Github for future reference.

That at least would be what everyone does. That way it will be true whenever the value of i is less than N, so it makes sense to an accountant, it goes of 0 until value before in total number. Just be careful not to do i < N - 1 because this would not go to the last item, or do i <= N because it would go further and would make a mistake. It could, but it is not ideal to do i <= N - 1, is doing an unnecessary arithmetic operation and on some architectures the <= is slower than the <.

0

Error is on line 35

Substitute:

for (int i=0; i == N - 1; i++) {

for

for (int i=0; i < N; i++) {

The variable i is comparing to N and in fact it has to be smaller than N (i < N).

Another issue is that the loop starts at 0 and goes until it is smaller the variable N. From the moment he goes to check and i is equal to N it will not execute the block. So if you leave the i < N - 1; he will always count a minus.

  • 1

    Oh indeed, that’s really it. I thought putting i == N - 1 would do the repeat until leaving i with this value. Thank you

  • Do not forget to mark as answer ;D

  • 5

    @Luke is not very nice to induce the author to accept your answer, let him assess which of the answers is best, remember that the goal here is not accepted, is to share knowledge ;)

  • I only commented for him to mark as an answer because among the two answers he commented only mine, which by chance is receiving negative votes, having a more objective answer and answered before. Even because this is his first post and I believe he does not even know he has how to mark as an answer, my intention was not to induce that my answer is better and yes remind him that has this option.

  • 3

    Him stifle that worked, but making i < N - 1, as you suggested, the for will scroll through one less item (and maybe he hasn’t figured it out yet). So the negatives aren’t "by chance". The other answer has the correct code :-)

  • From what he presented he wants the user to enter the number that will set the vector size. If the user type 5, as in the example he used, the vector size, started at 0, will be 6 and not 5 as the user requested. I guess you didn’t read what he asked...

  • 3

    new int[N] creates an array with N elements. Using N equal to 5, the array has 5 elements (indexes from 0 to 4). Doing the for with i < N - 1, it will stop at index 3, leaving the last element (index 4) out.

  • 3

    Summarizing what @hkotsubo said, your code will cause loop to ignore the last item, I think you’re the one who didn’t understand your own code.

Show 3 more comments

Browser other questions tagged

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