2015-01-17 3 views
0

Я пытаюсь использовать сортировку вставки для сортировки для среднего уровня игроков. Я получаю сообщение об ошибке «Метод get (int) в типе java.util.ArrayList не применим для аргументов (double)» в строках S.get (внешний) и S.get (внутренний - 1)Baseball Menu Insertion sort part

Что я делаю неправильно? Как я могу это исправить?

import java.util.*; 
import java.io.*; 
class menu { 
    public static void main (String [] arg) throws IOException 
    { 

    PlayerRip.PlayerInfo obj5 = new PlayerRip.PlayerInfo(); 
    ArrayList<Player> obj6 = new ArrayList<Player>(); 
    MainMenu(obj5, obj6); 


    } 
    public static void MainMenu(PlayerRip P, ArrayList<Player> S) throws IOException 
    { 
    Scanner keyboard = new Scanner(System.in); 
    int response = 0; 
    int response2 = 0; 

    ArrayList<Player> obj1 = new ArrayList<Player>(); 
    obj1.add(new Player("Agostini", "Aldo", "Pitcher", 170, 20, 72, 12, 6, 1, 1, 0)); 
    do 
    { 
     System.out.println("1. Open A file:"); 
     System.out.println("7. Exit the program"); 
     response = keyboard.nextInt(); 

     switch (response) 
     { 
     case 1: 
     { 
      openFile(obj1); 

      do 
      { 
      System.out.println("2. Display all players"); 
      System.out.println("3. Enter player's Height"); 
      System.out.println("4. Sort all players alphabetically by Surname"); 
      System.out.println("5. Sort all players by batting average"); 
      System.out.println("6. Delete a player by selecting the player's surname from a list"); 
      System.out.println("7. Add a player to the stats"); 
      System.out.println("8. Save stats to a file"); 
      System.out.println("9. Exit the program"); 
      response2 = keyboard.nextInt(); 
      switch (response2) 
      { 
       case 2: 
       { 
       displayInfo(obj1); 
       break; 
       } 
       case 3: 
       { 
       changeHeight(obj1); 
       break; 
       } 
       case 4: 
       { 
       BubbleSort(obj1); 
       break; 
       } 
       case 5: 
       { 
       break; 
       } 
       case 6: 
       { 
       deletePlayerInfo(obj1); 
       break; 
       } 
       case 7: 
       { 
       addPlayerInfo(obj1); 
       break; 
       } 
       case 8: 
       { 
       saveFile(obj1); 
       break; 
       } 
       case 9: 
       { 
       System.exit(0); 
       break; 
       } 

      } 
      } while (response2 != 9); 
      break; 
     } 
     case 7: 
     { 
      System.exit(0); 
      break; 
     } 
     } 
    } while (response != 1 || response != 7); // End of switch statement 

    } 
    public static void displayInfo(ArrayList<Player> S) { 
    System.out.printf("%10s %10s %10s \t %4s %4s \t %4s \t %4s %4s \t %4s %4s %4s \n", "Surname", "GivenName", "Postition", "Height(cm)", "Hits", "AtBats", "Singles", "Doubles", "Triples", "HomeRuns", "Batting Average"); 
    for (int index = 0; index < S.size(); index++) 
     S.get(index).displayInfo(); 
    } 

    public static void openFile(ArrayList<Player> S) throws IOException // This method allows the oepning of files into the program 
    { 
    Scanner userInput = new Scanner(System.in); 
    String fileName; 
    S.removeAll(S); // Empties the list readies it for a new oned 


    System.out.println("Enter a file name to open: "); 
    fileName = userInput.next().trim(); 
    File file = new File(fileName); 

    if (file.exists()) // Checks whether or not the file exists in the directory 
    { 
     Scanner fileInput = new Scanner(file); 
     while (fileInput.hasNext()) 
     { 
     S.add(new Player(fileInput.next(), fileInput.next(), fileInput.next(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextInt(), fileInput.nextDouble())); // If it exists it adds the token values into the respective lists 
     } 
     fileInput.close(); // Closes further file input 
    } 
    else // Error message incase the file-name is not valid 
     System.out.println("FILE NOT FOUND"); 




    } 

    public static void saveFile(ArrayList<Player> S) throws IOException // This method allows for the saving of values to an external file 
    { 
    Scanner inputInfo = new Scanner(System.in); 
    String fileName; 
    System.out.println("Enter a file name to save the info with:"); 
    fileName = inputInfo.next().trim(); 
    File file = new File(fileName); 
    PrintStream writeFile = new PrintStream(file); 

    for (int i = 0; i < S.size(); i++) // Gathers all values and prints them to the file in their respective format 
    { 
     writeFile.print(S.get(i).getName() + " "); 
     writeFile.print(S.get(i).getName2() + " "); 
     writeFile.print(S.get(i).getPosition() + " "); 
     for (int j = 0; j < 7; j++) 
     writeFile.print(S.get(i).getMark(j) + " "); 
     for (int j = 0; j < 1; j++) 
     writeFile.print(S.get(i).getBatAvg(j)); 
     writeFile.println(" "); 
    } 
    writeFile.close(); // Stops any further writing to the file 
    } 

    public static void deletePlayerInfo(ArrayList<Player> S) // THis method allows the user to delete any player within the list 
    { 
    int deleteIt = 0; 
    Scanner keyboard = new Scanner(System.in); 
    System.out.println("Please select the number of the player to be deleted: "); 
    for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players 
    { 
     System.out.print(i + ". " + S.get(i).getName()); 
     System.out.println(" "); 
    } 
    deleteIt = keyboard.nextInt(); 
    S.remove(deleteIt); 
    } 

    public static void addPlayerInfo(ArrayList<Player> S) // This method allows the user to add a new player to the list 
    { 
    String firstName = ""; 
    String surName = ""; 
    String posName = ""; 
    int heightVal = 0; 
    int hitsVal = 0; 
    int atBatsVal = 0; 
    int singVal = 0; 
    int doubVal = 0; 
    int tripVal = 0; 
    int homeVal = 0; 


    Scanner keyboard = new Scanner(System.in); // Various user input 
    System.out.println("Enter the surname and name of the new player: "); 
    System.out.println("Surname: "); 
    surName = keyboard.nextLine(); 
    System.out.println("Name: "); 
    firstName = keyboard.nextLine(); 
    System.out.println("Enter the position of the new player: "); 
    System.out.println("Position: "); 
    posName = keyboard.nextLine(); 
    System.out.println("Enter the height of the new player: "); 
    heightVal = keyboard.nextInt(); 
    System.out.println("Enter the batting statistics: "); 
    System.out.println("Hits: "); 
    hitsVal = keyboard.nextInt(); 
    System.out.println("AtBats: "); 
    atBatsVal = keyboard.nextInt(); 
    System.out.println("Singles: "); 
    singVal = keyboard.nextInt(); 
    System.out.println("Doubles: "); 
    doubVal = keyboard.nextInt(); 
    System.out.println("Triples: "); 
    tripVal = keyboard.nextInt(); 
    System.out.println("HomeRuns: "); 
    homeVal = keyboard.nextInt(); 
    S.add(new Player(surName, firstName, posName, heightVal, hitsVal, atBatsVal, singVal, doubVal, tripVal, homeVal, 0)); 
    } 

    public static void changeHeight(ArrayList<Player> S) 
    { 
    int playerSel = 0; 
    int newHeight = 0; 
    Scanner keyboard = new Scanner(System.in); // Various user input 
    System.out.println("Select a player to enter the height for: "); 

    do 
    { 
     for (int i = 0; i < S.size(); i++) // Displays only the first/surNames of the players 
     { 
     System.out.print(i + ". " + S.get(i).getName()); 
     System.out.println(" "); 
     } 
     playerSel = keyboard.nextInt(); 
     System.out.println("Enter the height for this character: "); 
     newHeight = keyboard.nextInt(); 
     if (newHeight < 125 && newHeight > 240) 
     { 
     System.out.println("WRONG! TRY AGAIN!"); 
     } 
     else 
     { 

     } 
    } while (newHeight >= 125 && newHeight <= 240); 
    } 

    public static void BubbleSort(ArrayList<Player> S){ 
    Player strTemp; 
    int i = 0; 
    boolean isSorted = false; 
    while(i < S.size()&&isSorted==false) 
    { 
     isSorted = true; 
     for(int j = 0; j < (S.size()-1)-i;j++) 
     { 
     if(S.get(j).getName().compareToIgnoreCase(S.get(j+1).getName())>0){ 
      strTemp = S.get(j); 
      S.set(j,S.get(j+1)); 
      S.set(j+1,strTemp); 
      isSorted = false; 
     } 
     } 
     i++;} 
    } 
    public static void InsertionSort(ArrayList<Player> S){ // hits over atbats 
    int outer; 
    double inner; 
    for(outer = 1; outer < S.size();outer++){ 
    double keyItem = S.get(outer).getBatAvg(); 
     inner = outer - 1 ; 

     while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){ 
     S.set((inner),S.get(inner-1)); 
     inner--; 
     break; 
     } 
     double helpSort = S.get(inner).getBatAvg(); 
     helpSort = keyItem; 
    } 
    } 

} 
class PlayerRip { 
    public String name; 
    public String name2; 
    public String position; 
    public int [ ] mark = new int[7]; 
    public double [ ] batAvg = new double[1]; 


    static class PlayerInfo extends PlayerRip 
    { 
    PlayerInfo() { 
     this.name = "-1"; 
     this.name2 = "-1"; 
     this.position = "-1"; 
     for (int i=0; i < mark.length; i++) 
     mark[i] = -1; 
    } 

    PlayerInfo(String nam, String nam2, String pos, int a, int b, int c, int d, int e, int f, int g, double h) { 
     this.name = nam; 
     this.name2 = nam2; 
     this.position = pos; 
     this.mark[0] = a; this.mark[1] = b; this.mark[2] = c; this.mark[3] = d; this.mark[4] = e; this.mark[5] = f; this.mark[6] = g; 
     batAvg[0] = (((double)mark[1]/(double)mark[2]) * 100); 
    } 

    public void setName(String nam) { name = nam; } 
    public void setName2(String nam2) { name2 = nam2; } 
    public void setPosition(String pos) { position = pos; } 
    public void setMark(int index, int mark) { this.mark[index] = mark; } 
    public void setBatAvg(int index, double batAvg) {this.batAvg[index] = batAvg;} 
    public String getName() { return this.name; } 
    public String getName2() { return this.name2; } 
    public String getPosition() { return this.position; } 
    public double getBatAvg() { return this.batAvg[0];} 
    public int getMark(int index) { return this.mark[index]; } 
    public void setHeight(int index, int mark) { this.mark[index] = mark; } 
    public int getHeight(int index) { return this.mark[0]; } 

    public void setHits (int index, int mark) { this.mark [index] = mark; } 
    public int getHits (int index) { return this.mark [1]; } 
    public void setAtBats (int index, int mark) { this.mark [index] = mark; } 
    public int getAtBats(int index) { return this.mark [2]; } 
    public void setSingles (int index, int mark) { this.mark [index] = mark; } 
    public int getSingles (int index) { return this.mark [3] ; } 
    public void setDoubles (int index, int mark) { this.mark [index] = mark; } 
    public int getDoubles (int index) { return this.mark [4] ; } 
    public void setTriples (int index, int mark) { this.mark [index] = mark; } 
    public int getTriples (int index) { return this.mark [5] ; } 
    public void setHomeRuns (int index, int mark) { this.mark [index] = mark; } 
    public int getHomeRuns (int index) { return this.mark [6] ; } 




    } 


} 

жаль формата им новое на сайте

} 
    public static void InsertionSort(ArrayList<Player> S){ // hits over atbats 
    int outer; 
    double inner; 
    for(outer = 1; outer < S.size();outer++){ 
    double keyItem = S.get(outer).getBatAvg(); 
     inner = outer - 1 ; 

     while(inner >0&&S.get(inner-1).getBatAvg() > keyItem){ 
     S.set((inner),S.get(inner-1)); 
     inner--; 
     break; 
     } 
     double helpSort = S.get(inner).getBatAvg(); 
     helpSort = keyItem; 
    } 
    } 

} 

удельная площадь проблем

ответ

0

S.get() и S.set() взять переменную INT так отбрасывать внутренний к междунар.

0

Вы определили inner как double, и в Java, когда вы делаете математику с double и int (например, inner - 1), вы получите double в качестве результата. This page имеет довольно хорошее объяснение.

Тогда, когда вы говорите S.get(inner - 1), вы говорите, что используете double в качестве индекса в ArrayList. documentation for ArrayList.get говорит, что вы можете использовать только int в качестве индекса, и именно поэтому вы получаете ошибку компилятора. Вам также разрешено использовать только int в качестве индекса для set, поэтому компилятор будет жаловаться на S.set(inner, ...).

Вы можете просто бросить inner к int, но было бы гораздо лучше, чтобы объявить его как int в первую очередь, так как нет никакой причины, она должна быть double.

+0

Я попытался объявить их как int, но сортировка вставки не работает – drbajwa

+0

Я получаю 0 ошибок, но это не работает, есть ли другой способ использования сортировки вставки для организации их с самого высокого до самого низкого значения batg. – drbajwa

+0

Несколько вещей, которые помогут вам начать ... Посмотрите на свой цикл while. Поскольку это написано прямо сейчас, оно будет работать только один раз. Также похоже, что ваша переменная 'helpSort' не делает ничего полезного. – ecraig12345

Смежные вопросы