john john - 1 month ago 6
Java Question

finding how many consecutive numbers in an array [java]

For example, array is like this {1,1,2,1,1,1 } and they key int is 1, the Largest number of consecutive times 1 is going to be 3. When i run my code and type the same numbers, I'm getting 4 consecutive numbers of 1. Can someone give me advice? is there a built-in method that will help me solve this?

Scanner kbd = new Scanner (System.in);
int count = 1;
int largest = 0;

System.out.println("Enter number");
int numbers = kbd.nextInt();
int[] numb = new int[numbers];
System.out.println("Now enter "+numbers+" integers:");
for(int i =0; i<numb.length;i++){
numb[i] = kbd.nextInt();
}
System.out.println("Now enter the key integer: ");
int key = kbd.nextInt();

for (int i = 0; i<numb.length-1; i++) {
if (numb[i] == key) {
if (numb[i] == numb[i + 1]) {
count++;
}
else {
largest = Math.max(largest, count);
count = 1;

}
}
}

System.out.println("Largest number of consecutive times "+key+" was entered: "+largest);

Answer

A slightly different approach.

count = 0;
for (int i : numb){
  if (i == key){
    count++;
  } else {
    count = 0;
  }
  if(largest<count) {
    largest = count;
  }
}
Comments