2014-04-20 4 views
0

У меня проблемы с другой программой (им просто не хорошо с модулями и массивами). может ли кто-нибудь помочь мне заставить его работать правильно? работал над ним всю ночь, и я очень устал ... в любом случае вот код, сделанный до сих пор. проблема возникает:Java: сортировка/поиск массива

Создайте программу, которая просит пользователя ввести 10 баллов в гольф. Оценки должны храниться в массиве Integer. Сортируйте массив в в порядке возрастания и покажите его содержимое.

import java.util.Scanner; 

public class SortedGolfScoresIB 
{ 
    public static void main(String[] args) 
    { 
     //local variables 
     final int SIZE = 10; 
     int[] scores = new int[SIZE]; 

     // get the scores 
     getScores(scores, SIZE); 

     // sore the scores in ascending order 
     insertionSort(scores, SIZE); 

     //display the results in ascending order 
     displayScores(scores, SIZE); 
    } 

    // the getScoresmodule prompts the user for 
    // golf scores to populare the scores array. 

    public static void getScores(int scores[], int size) 
    { 
     // local variable for loop index 
     int index; 


     // get the scores 
     for (index = 0; index <=size; size--) 
     { 
      System.out.println("Enter golf score number " + index +1 + ":"); 
      Scanner keyboard = new Scanner(System.in); 
      scores[index] = keyboard.nextInt(); 
     } 

     } 
     // the insertionSort module sorts the contents of the array 
     // in ascending order 
     public static void insertionSort(int array[], int size) 
     { 
      //local variables 
      int index; 
      int scan; 
      int unsortedValue; 

      for (index = 1; index <=size; size--) 
      { 
       unsortedValue = array[index]; 
       scan = index; 
      } 

      while (scan > 0 && array[scan-1] < array [scan]) 
      { 
       swap (array[scan-1], array[scan]); 
       scan = scan -1; 
      } 

     array[scan] = unsortedValue; 
     } 

     //the swap module swaps the contents of its two arguments 
     public static void swap(int a, int b) 
     { 
      int temp; 
      //swap a and b 
      temp = a; 
      a = b; 
      b = temp; 
     } 

     // the display scores module displays the 
     // golve scores in the scores array 
     public static void displayScores(int scores[], int size) 
     { 

      // local variable for loop index 
      int index; 

      //display the scores 
      System.out.println ("here are the scores: "); 
      for (index=0; index <= size; size--) 
      { 
       System.out.println(scores[index]); 
      } 
     } 
    } 

может кто-нибудь помочь мне получить эту работу и без ошибок?

Edit1: я обновил код, и вот что у меня есть сейчас

import java.util.Scanner; 

public class SortedGolfScoresIB 
{ 
    public static void main(String[] args) 
    { 
     //local variables 
     final int SIZE = 10; 
     int[] scores = new int[SIZE]; 

     // get the scores 
     getScores(scores, SIZE); 

     // sore the scores in ascending order 
     insertionSort(scores, SIZE); 

     //display the results in ascending order 
     displayScores(scores, SIZE); 
    } 

    // the getScoresmodule prompts the user for 
    // golf scores to populare the scores array. 

    public static void getScores(int scores[], int size) 
    { 
     // local variable for loop index 
     int index; 


     // get the scores 
     for (index = 0; index <=size; index++) 
     { 
      System.out.println("Enter golf score number " + (index +1) + ":"); 
      Scanner keyboard = new Scanner(System.in); 
      scores[index] = keyboard.nextInt(); 
     } 

     } 
     // the insertionSort module sorts the contents of the array 
     // in ascending order 
     public static void insertionSort(int array[], int size) 
     { 
      //local variables 
      int index; 
      int scan; 
      int unsortedValue; 

      for (index = 1; index <=size; index++) 
      { 
       unsortedValue = array[index]; 
       scan = index; 
       array[scan] = unsortedValue; 

       } 

      while (scan > 0 && array[scan-1] < array [scan]) 
      { 
       swap (array[scan-1], array[scan]); 
       scan = scan -1; 
      } 

     } 

     //the swap module swaps the contents of its two arguments 
     public static void swap(int a, int b) 
     { 
      int temp; 
      //swap a and b 
      temp = a; 
      a = b; 
      b = temp; 
     } 

     // the display scores module displays the 
     // golve scores in the scores array 
     public static void displayScores(int scores[], int size) 
     { 

      // local variable for loop index 
      int index; 

      //display the scores 
      System.out.println ("here are the scores: "); 
      for (index=0; index <= size; index++) 
      { 
       System.out.print(scores[index]); 
      } 
     } 
    } 

И.М. Ошибка при получении в настоящее время является то, что «сканирование» в моем цикле, пока не инициализируется.

редактировать 2:

получил программу для работы и компиляции правильно, но его не выводит все оценки в конце в порядке возрастания, как это должно быть.

import java.util.Scanner; 

public class SortedGolfScoresIB 
{ 
    public static void main(String[] args) 
    { 
     //local variables 
     final int SIZE = 10; 
     int[] scores = new int[SIZE]; 

     // get the scores 
     getScores(scores, SIZE); 

     // sore the scores in ascending order 
     insertionSort(scores, SIZE); 

     //display the results in ascending order 
     displayScores(scores, SIZE); 
    } 

    // the getScoresmodule prompts the user for 
    // golf scores to populare the scores array. 

    public static void getScores(int scores[], int size) 
    { 
     // local variable for loop index 
     int index; 


     // get the scores 
     for (index = 0; index <=size; index++) 
     { 
      System.out.println("Enter golf score number " + (index +1) + ":"); 
      Scanner keyboard = new Scanner(System.in); 
      scores[index] = keyboard.nextInt(); 
     } 

     } 
     // the insertionSort module sorts the contents of the array 
     // in ascending order 
     public static void insertionSort(int array[], int size) 
     { 
      //local variables 
      int index; 
      int scan; 
      int unsortedValue; 

      for (index = 1; index <=size; index++) 
      { 
       unsortedValue = array[index]; 
       scan = index; 

       array[scan] = unsortedValue; 



      while (scan > 0 && array[scan-1] < array [scan]) 

       swap (array[scan-1], array[scan]); 
       scan = scan -1; 
      } 

     } 

     //the swap module swaps the contents of its two arguments 
     public static void swap(int a, int b) 
     { 
      int temp; 
      //swap a and b 
      temp = a; 
      a = b; 
      b = temp; 
     } 

     // the display scores module displays the 
     // golve scores in the scores array 
     public static void displayScores(int scores[], int size) 
     { 

      // local variable for loop index 
      int index; 

      //display the scores 
      System.out.println ("here are the scores: "); 
      for (index=0; index <= size; index++) 
      { 
       System.out.print(scores[index]); 
      } 
     } 
    } 

код компилируется и работает, но не выводит содержимое массива. im получая ошибку за пределами границ.

изменить 3: зафиксировать ошибку за пределы, изменив «индекс < = размер« до »индекс < размер». но ошибка im get now заключается в том, что мой код просто останавливается после ввода всех 10 баллов и не отображает содержимое массива, как я упоминал ранее.

import java.util.Scanner; 

public class SortedGolfScoresIB 
{ 
    public static void main(String[] args) 
    { 
     //local variables 
     final int SIZE = 10; 
     int[] scores = new int[SIZE]; 

     // get the scores 
     getScores(scores, SIZE); 

     // sore the scores in ascending order 
     insertionSort(scores, SIZE); 

     //display the results in ascending order 
     displayScores(scores, SIZE); 
    } 

    // the getScoresmodule prompts the user for 
    // golf scores to populare the scores array. 

    public static void getScores(int scores[], int size) 
    { 
     // local variable for loop index 
     int index; 


     // get the scores 
     for (index = 0; index <=size; index++) 
     { 
      System.out.println("Enter golf score number " + (index +1) + ":"); 
      Scanner keyboard = new Scanner(System.in); 
      scores[index] = keyboard.nextInt(); 
     } 

     } 
     // the insertionSort module sorts the contents of the array 
     // in ascending order 
     public static void insertionSort(int array[], int size) 
     { 
      //local variables 
      int index; 
      int scan; 
      int unsortedValue; 

      for (index = 1; index <=size; index++) 
      { 
       unsortedValue = array[index]; 
       scan = index; 

       array[scan] = unsortedValue; 



      while (scan > 0 && array[scan-1] < array [scan]) 

       swap (array[scan-1], array[scan]); 
       scan = scan -1; 
      } 

     } 

     //the swap module swaps the contents of its two arguments 
     public static void swap(int a, int b) 
     { 
      int temp; 
      //swap a and b 
      temp = a; 
      a = b; 
      b = temp; 
     } 

     // the display scores module displays the 
     // golve scores in the scores array 
     public static void displayScores(int scores[], int size) 
     { 

      // local variable for loop index 
      int index; 

      //display the scores 
      System.out.println ("here are the scores: "); 
      for (index=0; index <= size; index++) 
      { 
       System.out.print(scores[index]); 
      } 
     } 
    } 

3-й и, надеюсь, последний измененный код. может ли кто-нибудь помочь мне с этим последним бит?

+1

Не могли бы вы разместить свой ввод/вывод и желаемый результат? – Matthew

+1

Добро пожаловать в переполнение стека! Просить людей обнаружить ошибки в коде не особенно продуктивно. Вы должны использовать отладчик (или добавить заявления печати), чтобы изолировать проблему, отслеживая ход вашей программы и сравнивая ее с тем, что вы ожидаете. Как только двое расходятся, вы нашли свою проблему. (И затем, если необходимо, вы должны создать [минимальный тестовый сценарий] (http://stackoverflow.com/help/mcve).) –

+0

Какая проблема вы сталкиваетесь? ошибка компиляции/выполнения или нежелательный вывод или что? – maxx777

ответ

0

Все для loops в вашей программе получают доступ к одному и тому же индексу из массива баллов.

Изменения цикла: size-- к index++ следующему

for (index = 0; index <=size; index++) <br> 
{ 
//Your code 
} 
0

Ну, обычно я бы опубликовал это как комментарий, так как я все еще не уверен, чего вы точно хотите; однако есть такой код, который я не могу.

Но вы ищете программу делает именно это:

import java.util.Scanner; 
import java.util.LinkedList; 
import java.util.Comparator; 

public class SortedGolfScoresIB { 

    public static void main(String[] args) { 
     //local variables 
     final int SIZE = 10; 
     LinkedList<Integer> scores; 
     // get the scores 
     scores = getScores(SIZE); 
     // sore the scores in ascending order 
     insertionSort(scores); 
     //display the results in ascending order 
     displayScores(scores); 
    } 

    // the getScoresmodule prompts the user for 
    // golf scores to populare the scores array. 
    public static LinkedList<Integer> getScores(int size) { 
     LinkedList<Integer> result = new LinkedList<Integer>(); 
     // get the scores 
     for (int index = 0; index < size; index++) { 
      System.out.println("Enter golf score number " + (index + 1) + ":"); 
      Scanner keyboard = new Scanner(System.in); 
      result.add(keyboard.nextInt()); 
     } 
     return result; 
    } 
    public static void insertionSort(LinkedList<Integer> array) { 
     //local variables 
     java.util.Collections.sort(array, new Comparator<Integer>() { 

      @Override 
      public int compare(Integer o1, Integer o2) { 
       return o1 - o2; 
      } 

     }); 
    } 

    public static void displayScores(LinkedList<Integer> scores) { 
     //display the scores 
     System.out.println("here are the scores: "); 
     for (Integer score: scores) { 
      System.out.println(score); 
     } 
    } 
} 
+0

Я внес изменения в мой первоначальный вопрос, возможно, это поможет немного. – user3530421

0

Вы не инкрементируется индекс в цикл из getScores() метод вместо вы уменьшить размер, поэтому он не будет читать элементы в массивы должностей всегда всегда оценивают [0], получает только значение и, следовательно, ваши значения чтения не добавляются к массиву.

так что лучше изменить его от for (index = 0; index <=size; size--) к for (index = 0; index <size; index++) см ниже рабочей программы и дайте мне знать, за любую помощь

public class SortedGolfScoresIB 
{ 
    public static void main(String[] args) { 
     final int SIZE = 10; 
      int[] scores = new int[SIZE]; 
      int[] input =getScores(scores, SIZE); 
      insertionSort(input); 
     } 
    public static int[] getScores(int scores[], int size) 
     { 
      // local variable for loop index 
      int index; 


      // get the scores 
      for (index = 0; index <size; index++) 
      { 
       System.out.println("Enter golf score number " + index +1 + ":"); 
       Scanner keyboard = new Scanner(System.in); 
       scores[index] = keyboard.nextInt(); 
      } 
      return scores; 

      } 
     private static void printNumbers(int[] input) { 

      for (int i = 0; i < input.length; i++) { 
       System.out.print(input[i] + ", "); 
      } 
      System.out.println("\n"); 
     } 

     public static void insertionSort(int array[]) { 
      int n = array.length; 
      for (int j = 1; j < n; j++) { 
       int key = array[j]; 
       int i = j-1; 
       while ((i > -1) && (array [i] > key)) { 
        array [i+1] = array [i]; 
        i--; 
       } 
       array[i+1] = key; 

      } 
      printNumbers(array); 
     } 
} 
+0

это хорошо, но программа, которую я делаю, должна быть модульной. – user3530421

+0

Да, вы можете достичь того же с указанными изменениями. –

+0

Я внес изменения в свой первоначальный код. я придерживался того, что я собирался, поскольку я не хотел, чтобы действительно копировать другие. вы видите, что не так с моей версией? единственное, что не так с ним сейчас, это то, что он не отображает оценки. – user3530421

0

Читая вопрос, естественно разбивается на четыре части:

  • спросить пользователь вводит десять баллов в гольф.

  • хранить десять баллов в целочисленном массиве.

  • сортировать массив в порядке возрастания.

  • отображает содержимое отсортированного массива.

Вы написали короткие фрагменты кода для выполнения этих четырех отдельных задач. Теперь вам нужно проверить, что вы получаете то, что ожидаете от каждого из четырех фрагментов кода, выписывая текущее состояние ваших данных на каждом переходе. Посмотрите на промежуточные данные и сравните их с тем, что вы ожидаете увидеть. Это скажет вам, где ваш код не работает.

Сначала попробуйте исправить любые детали, которые не сработают сами. Если вы все еще застряли, отправьте здесь код ошибки и сообщите нам, что вы уже пробовали, чтобы исправить его. В противном случае вы получите некоторые предложения «Пробовали ...», где вы отвечаете: «Да, я уже пробовал это».

Чем больше работы вы показываете, тем более вероятно, что мы помогаем вам справиться с вашей проблемой.

+0

Я исправил большую часть его, и теперь я получаю одну ошибку, которая говорит, что «сканирование» не инициализируется в моем цикле while. Я добавил в редактирование в оригинальном вопросе. – user3530421

+0

прочитайте редактирование в моем исходном вопросе для получения дополнительной информации, im update, поскольку я иду – user3530421

0

я получил код для работы, как я хотел! вот окончательный код

import java.util.Scanner; 

public class SortedGolfScoresIB 
{ 
    public static void main(String[] args) 
    { 
     //local variables 
     final int SIZE = 10; 
     int[] scores = new int[SIZE]; 

     // get the scores 
     getScores(scores, SIZE); 

     // sore the scores in ascending order 
     insertionSort(scores, SIZE); 

     //display the results in ascending order 
     displayScores(scores, SIZE); 
    } 

    // the getScoresmodule prompts the user for 
    // golf scores to populare the scores array. 

    public static void getScores(int scores[], int size) 
    { 
     // local variable for loop index 
     int index; 


     // get the scores 
     for (index = 0; index < size; index++) 
     { 
      System.out.println("Enter golf score number " + (index +1) + ":"); 
      Scanner keyboard = new Scanner(System.in); 
      scores[index] = keyboard.nextInt(); 
     } 

     } 
     // the insertionSort module sorts the contents of the array 
     // in ascending order 
     public static void insertionSort(int array[], int size) 
     { 
      //local variables 
      int index; 
      int scan; 
      int unsortedValue; 

      for (index = 1; index < size; index++) 
      { 
       unsortedValue = array[index]; 
       scan = index; 

       array[scan] = unsortedValue; 



      while (scan > 0 && array[scan-1] < array [scan]) 
       { 
       swap(array[scan-1], array[scan]); 
       scan = scan -1; 
      } 
     } 

     } 

     //the swap module swaps the contents of its two arguments 
     public static void swap(int a, int b) 
     { 
      int temp; 
      //swap a and b 
      temp = a; 
      a = b; 
      b = temp; 
     } 

     // the display scores module displays the 
     // golve scores in the scores array 

     public static void displayScores(int scores[], int size) 
     { 

      // local variable for loop index 
      int index; 

      //display the scores 
      System.out.println ("here are the scores: "); 

      for (index=0; index < size; index++) 
      { 
       System.out.println(scores[index]); 
      } 
     } 
    } 

благодарит всех за помощь.

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