Reputation: 201
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);
Upvotes: 1
Views: 12556
Reputation: 2080
Try with this.
int numb[] = new int[] { 6, 3, 3, 5,5,5 ,3, 5, 15,15 };
int key = 3; // Can be changed
int largest = 0;
int currCount = 0;
for (int i = 0; i < numb.length; i++) {
if (numb[i] == key) {
currCount++;
} else {
if (currCount > largest) {
largest = currCount;
}
currCount = 0;
}
}
if (currCount > largest) {
largest = currCount;
}
System.out.println("Largest number of consecutive times " + key + " was entered: " + largest);
Upvotes: 0
Reputation: 2530
for (int i = 0; i<numb.length; i++) {
if (numb[i] == key) {
if(i == numb.length-1){
count =1;
}
else if (numb[i] == numb[i+1]) {
count++;
}
if (count > largest) {
largest = count;
}
}
else
count = 1;
}
Upvotes: 0
Reputation: 901
Just reassign count
to 0
in the if condition (In your initial code before editing).
if(largest<count){
largest = Math.max(largest, count);
count = 0;
}
And in the current code just add a if condition checking whether largest is greater than count after the for loop.
largest = (largest > count) ? largest : count;
Or
if (count > largest){
largest = count;
}
Upvotes: 0
Reputation: 2016
A slightly different approach.
count = 0;
for (int i : numb){
if (i == key){
count++;
} else {
count = 0;
}
if(largest<count) {
largest = count;
}
}
Upvotes: 2
Reputation: 198103
It doesn't look like you should have a second inner loop, it should just be
for (int i = 0; i + 1<numb.length; i++){
if(numb[i] == numb[i + 1]){
count++;
}else{
if(largest<count) {
largest = count;
count = 1;
}
}
Upvotes: 1