2

I'm new to java and im trying to write a program that gets an undefined amount of integers and tells you the longest order of the same integer.

public class Search{
  public static void main(String args[]){


    int order[] = new int[args.length];
    for(int i = 0;i < args.length;i++){        //Input into array
      order[i] = Integer.parseInt(args[i]);
    }
    int count = 0;
    int temp_count = 0;
    int pos = -1;
    int temp_pos = -1;
    boolean search = false;

    for(int i = 1; i < args.length;i++){
      if(order[i-1] != order[i]){
        temp_count = 1;                    //line of the same integers?
        search = true;
        temp_pos++;
      } else if(search && order[i-1] == order[i]){ // How long is the line?
          temp_count++;
      } else if(search && order[i-1] != order[i]){ // Does the line end?
          if (temp_count > count){
            count = temp_count;             // Update old length and position
            pos = temp_pos;
          }
          search = false;
      }
    }
    System.out.println("length: " + count);    //output
    System.out.println("position " + pos);
  }
}

The output is 0 and -1 , what should only be the case if there is no order of the same integers.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
Shattro
  • 27
  • 2

1 Answers1

2

In your if statement you are checking twice the same condition in the if and in the else if.
And this condition will never happen:

} else if(search && order[i-1] != order[i]){ 

In this way all variables remain count = 0; and pos = -1;

  if(order[i-1] != order[i]){
    //...
  } else if(search && order[i-1] != order[i]){ 
    // never run!! 
    //...
    count = temp_count;     
    pos = temp_pos;  
  }
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • 1
    Ty for your help. I realised, that i dont need the first if statement and could just use the second statement to verify if its an order. – Shattro Sep 05 '19 at 23:21