Advertisement
Guest User

Untitled

a guest
Feb 20th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.ArrayList;
  4. import java.util.Scanner;
  5.  
  6. public class RankingTest {
  7.     private String id[];
  8.     private int score[];
  9.  
  10.     public RankingTest() {
  11.         File prog408a = new File("prog408a.dat");
  12.  
  13.         try {
  14.             Scanner scanner = new Scanner(prog408a);
  15.             ArrayList<String> lines = new ArrayList<>();
  16.             // parse file into list
  17.             while (scanner.hasNextLine()) {
  18.                 lines.add(scanner.nextLine());
  19.             }
  20.  
  21.             id = new String[lines.size()];
  22.             score = new int[lines.size()];
  23.  
  24.             // fill arrays
  25.             for (int i = 0; i < lines.size(); i++) {
  26.                 String[] line = lines.get(i).split(" ");
  27.                 id[i] = line[0];
  28.                 score[i] = Integer.parseInt(line[1]);
  29.             }
  30.  
  31.             this.bubbleSort();
  32.             this.printScores();
  33.  
  34.         } catch (FileNotFoundException e) {
  35.             System.out.println("File not found!");
  36.             e.printStackTrace();
  37.         }
  38.  
  39.     }
  40.  
  41.     private void bubbleSort() {
  42.         int swaps = 0;
  43.         do {
  44.             swaps = 0;
  45.             for (int i = 1; i < score.length; i++) {
  46.                 if (score[i - 1] < score[i]) {
  47.                     int temp = score[i - 1];
  48.                     score[i - 1] = score[i];
  49.                     score[i] = temp;
  50.                     String temp2 = id[i - 1];
  51.                     id[i - 1] = id[i];
  52.                     id[i] = temp2;
  53.                     swaps++;
  54.                 }
  55.             }
  56.         } while (swaps > 0);
  57.         // stop after a full pass without swapping
  58.     }
  59.  
  60.     private void printScores() {
  61.         System.out.println("ID   Score");
  62.         for (int i = 0; i < id.length; i++) {
  63.             System.out.println(id[i] + "  " + score[i]);
  64.         }
  65.     }
  66.  
  67.     public static void main(String[] args) {
  68.         new RankingTest();
  69.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement