数组中的Java双输入

时间:2017-09-25 16:15:11

标签: java arrays input

我对数组输入有疑问。我必须创建程序,它将输入数字n(学生数)然后我必须输入学生的索引,并且得分.Score必须是从最低的最高.I已经做到了,但问题是我的索引不会“跟随”我的分数.Ex。

  • n = 3
  • 输入第一个数字是索引,第二个得分!
  • 1 - 2
  • 2 - 4
  • 3 - 5
  • 输出:
  • 1 - 5
  • 2 - 4
  • 3 - 2
  • 问题是我的索引不会出现在我的分数
  • 我的代码如下: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();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

因为你没有交换index[]数组:

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

答案 1 :(得分:0)

当您在score数组中交换元素时,请在index数组中执行相应的交换

 int t;
 if (score[i] > score[j]) {
    t = score[j];
    score[j] = score[i];
    score[i] = t;

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

注意:通过使用适当的数据结构,还有很多其他更好的方法来处理/解决这个问题。

您可以创建一个单独的类来获得分数及其位置

private static class Score {
    private int score;
    private int position;
    Score(int score, int position) {
        this.score = score;
        this.position = position;
    }
    public String toString() {
        return position + " " + score;
    }
}

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

List<Score> scores = new ArrayList<>();
for (int i = 0; i < n; i++) {
    int score = sc.nextInt();
    scores.add(new Score(score, i + 1)); //Create new Score objects
}
//Your sorting code here
//OR
//scores.sort((s1, s2) -> s1.score - s2.score); //Sort it by increasing scores
//OR   
// scores.sort(Comparator.comparingInt(s -> s.score));
System.out.println(scores);