The program must able to decide which rating is the highest and the lowest. Test Case:
Rate 1: 237 Rate 2: 4303 Rate 3: -635 Rate 4: 715 Rate 5: 56
Test Output :
Ratings in Highest to Lowest order :
Rate 2 Rate 4 Rate 1 Rate 5 Rate 3
The Highest Rating is Rate 2 with the of 4303 The Lowest Rating is Rate 3 with the of -635
CodePudding user response:
import java.util.*;
public class HighestLowest { /** * @param args */ public static void main(String[] args) { try (//Create Object for Scanner class to get input from keyword Scanner g = new Scanner(System.in)) { System.out.print("Enter the value of N: "); //Declaring array int inputValue = g.nextInt(), temp; //Get input from keyword System.out.print("Input Rating Value Below\n"); int[]arr = new int[inputValue]; //Get all input from keyword for(int i = 0, j= 1; i <= inputValue && j <= inputValue;i , j ){ System.out.print("Rate " j ":"); arr[i]= g.nextInt(); } //Sort the given ratings for(int m=0;m<arr.length;m ){ for(int n=m 1;n<arr.length;n ){ if(arr[m]<arr[n]){ temp = arr[m]; arr[m]=arr[n]; arr[n]=temp; } } } //Output of sorted ratings System.out.print("Ratings in Highest to Lowest: \n"); for(int t: arr){ System.out.println("Rate : " t); } //assign first element of an array to largest and smallest int min = arr[0]; int max = arr[0];
for (int i = 0; i < arr.length; i ) {
if (arr[i] > max)
max = arr[i];
else if (arr[i] < min)
min = arr[i];
}
System.out.println("The Highest Rating is " max);
System.out.println("The Lowest Rating is " min);
}
}
} I TRIED THIS BEFORE BUT I CANT GET THE EXACT OUTPUT.
CodePudding user response:
Try this.
static void heighestToLowestOrder(int[] input) {
int length = input.length;
int[] ordered = IntStream.range(0, length)
.boxed()
.sorted(Comparator.comparingInt(i -> input[(int) i]).reversed())
.mapToInt(Integer::intValue)
.toArray();
System.out.println("Ratings in Highest to Lowest order :");
System.out.println();
IntStream.of(ordered)
.forEach(i -> System.out.printf("Rate %d%n", i 1));
System.out.println();
System.out.printf("The Highest Rating is Rate %d with the of %d%n",
ordered[0] 1, input[ordered[0]]);
System.out.printf("The Lowest Rating is Rate %d with the of %d%n",
ordered[length - 1] 1, input[ordered[length - 1]]);
}
public static void main(String[] args) {
int[] input = {237, 4303, -635, 715, 56};
heighestToLowestOrder(input);
}
output:
Ratings in Highest to Lowest order :
Rate 2
Rate 4
Rate 1
Rate 5
Rate 3
The Highest Rating is Rate 2 with the of 4303
The Lowest Rating is Rate 3 with the of -635