Quiz answer unable to print last element | Selenium Forum
G
Ganesh Posted on 10/01/2019

Hi,

The below quiz answer in java module 2 unable to print occurance of last element.

The last element is 311.

Q.4Print how many times has a number repeated in following array
int x[] ={1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};

Please correct.


A
Ashish Thakur Replied on 14/01/2019

Look at thi solution


public class PrintArrayRepitition {

public static void main(String[] args) {
int x[] ={1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,43,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};
//int x[] ={1,1,3,2,3,1,5};

for(int i=0;i<x.length;i++) {
for(int j=i+1;j<x.length;j++) {
if(x[i] > x[j]) {
int temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
}

for(int i=0;i<x.length;i++) {
System.out.println(x[i]);
}

boolean exit=false;
for(int i=0;i<x.length;i++) {
int count=0;
int j=i;
for(j=i;j<x.length;j++) {
//System.out.println(x[i]+"--"+x[j]);
if(x[i] == x[j]) {
count++;
}else {
break;
}

}
System.out.println(x[i]+"is repeated "+ count+" times");
i=j-1;

if(exit)
break;

}

}

}