У меня проблемы с другой программой (им просто не хорошо с модулями и массивами). может ли кто-нибудь помочь мне заставить его работать правильно? работал над ним всю ночь, и я очень устал ... в любом случае вот код, сделанный до сих пор. проблема возникает: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-й и, надеюсь, последний измененный код. может ли кто-нибудь помочь мне с этим последним бит?
Не могли бы вы разместить свой ввод/вывод и желаемый результат? – Matthew
Добро пожаловать в переполнение стека! Просить людей обнаружить ошибки в коде не особенно продуктивно. Вы должны использовать отладчик (или добавить заявления печати), чтобы изолировать проблему, отслеживая ход вашей программы и сравнивая ее с тем, что вы ожидаете. Как только двое расходятся, вы нашли свою проблему. (И затем, если необходимо, вы должны создать [минимальный тестовый сценарий] (http://stackoverflow.com/help/mcve).) –
Какая проблема вы сталкиваетесь? ошибка компиляции/выполнения или нежелательный вывод или что? – maxx777