I wrote a code to output the largest value of a sequence if numbers given by the user. If the user only inputs equal values the same output will be repeated the number of inputs given by the user.
The problem here is that even though I wrote an if condition to avoid the repetition of the same output but it doesn't work. I would really appreciate the help.
Problem:
int y = 0;
for(int i : a){
int v = 0;
if(i == a.get(0)){
y = y + 1;
}
for(int o : a){
if(i >= o){
v = v + 1;
}
}
if(y == a.size()){
System.out.println("Largest_num = "+a.get(0));
}
else if((v == a.size())&&(y != a.size())){
System.out.println("Largest_num = "+i);
}
Whole code:
import java.util.Scanner;
import java.util.ArrayList;
class Noice{
public static void main(String args[]){
Scanner obj = new Scanner(System.in);
System.out.println();
ArrayList<Integer>a = new ArrayList<Integer>();
System.out.print("Enter length: ");
int d = obj.nextInt();
System.out.println();
for(int i = 0; i < d; i++){
int c = i + 1;
System.out.print("Num"+c+" = ");
int b = obj.nextInt();
a.add(b);
}
int y = 0;
for(int i : a){
int v = 0;
if(i == a.get(0)){
y = y + 1;
}
for(int o : a){
if(i >= o){
v = v + 1;
}
}
if(y == a.size()){
System.out.println("Largest_num = "+a.get(0));
}
else if((v == a.size())&&(y != a.size())){
System.out.println("Largest_num = "+i);
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire