Bekir Production Bekir Production - 20 days ago 6
Java Question

Java double input in array

I have question about array input.I have to create program which will enter number n (number of students) and then i have to input index of student,and score.Score has to be from the highest from the lowest.I have made that but problem is that my index won't "follow" my score.Ex.


  • n = 3

  • Input first number is index,second score!

  • 1 - 2

  • 2 - 4

  • 3 - 5

  • Output :

  • 1 - 5

  • 2 - 4

  • 3 - 2

  • Well problem is that my index will not appear with my score

  • My code is in picture with this:Picture






package danl;

import java.util.Scanner;

public class Nizovi6 {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] index = new int[n];
int[] score = new int[n];
for (int i = 0; i < n; i++) {
index[i] = scanner.nextInt();
score[i] = scanner.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (score[i] > score[j]) {
int t = score[j];
score[j] = score[i];
score[i] = t;
}
}
}
for (int i = 0; i < n; i++) {
System.out.println(index[i] + " " + score[i]);
System.out.println();
}
}
}

Answer Source

Because of you didn't swap index[] array:

t = index[j];
index[j] = index[i];
index[i] = t;