
本文旨在指导 Java 初学者如何对数组中的元素进行排序,并按照特定的表格格式输出排序后的结果,同时保持原始索引信息的对应关系。通过修改现有的代码,我们将实现一个额外的输出,以展示按升序排列的测试分数,并保留它们在原始输入中的索引位置。
原始代码存在的问题在于,排序算法 selectionSort() 对整个数组进行排序,包括未使用的数组元素。这导致输出结果中包含大量的 0,并且索引信息没有正确保留。我们需要修改代码,使其仅对用户输入的有效分数进行排序,并输出排序后的分数及其对应的原始索引。
我们可以通过以下步骤解决问题:
以下是修改后的代码:
立即学习“Java免费学习笔记(深入)”;
import java.util.Scanner;
public class ArrayIntro2 {
public static void main(String[] args) {
//integer array
int[] TestGrades = new int[25];
//creating object of ArrayIntro2T
ArrayIntro2T pass = new ArrayIntro2T(TestGrades, 0, 0, 0);
//getting total and filling array
int scoreCount = ArrayIntro2T.FillArray(TestGrades, 0);
//get average score
double avg = pass.ComputeAverage(TestGrades, scoreCount);
//outputting table
ArrayIntro2T.OutputArray(TestGrades, scoreCount, avg);
// Outputting sorted table
ArrayIntro2T.selectionSort(TestGrades, scoreCount); // Sort only valid scores
ArrayIntro2T.OutputSortedArray(TestGrades, scoreCount);
}
}
//new class to store methods
class ArrayIntro2T {
//variable declaration
double CalcAvg = 0;
int ScoreTotal = 0;
int ScoreCount = 0;
int[] TestGrades = new int[25];
//constructor
public ArrayIntro2T(int[] TestGradesT, int ScoreCountT, double CalcAvgT, int ScoreTotalT) {
TestGrades = TestGradesT;
ScoreCount = ScoreCountT;
CalcAvg = CalcAvgT;
ScoreTotal = ScoreTotalT;
}
//method to fill array
public static int FillArray(int[] TestGrades, int ScoreCount) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter test scores one at a time, up to 25 values or enter -1 to quit");
TestGrades[ScoreCount] = scan.nextInt();
if (TestGrades[ScoreCount] == -1) {
System.out.println("You have chosen to quit ");
}
while (TestGrades[ScoreCount] >= 0 && ScoreCount < 25) { // Corrected the loop condition
ScoreCount++;
if (ScoreCount < 25) { // Added check to prevent ArrayIndexOutOfBoundsException
System.out.println("Enter the next test score or -1 to finish ");
TestGrades[ScoreCount] = scan.nextInt();
} else {
System.out.println("Maximum number of scores reached.");
break;
}
}
return ScoreCount;
}
//method to compute average
public double ComputeAverage(int[] TestGrades, int ScoreCount) {
for (int i = 0; i < ScoreCount; i++) {
ScoreTotal += TestGrades[i];
CalcAvg = (double) ScoreTotal / (double) ScoreCount;
}
return CalcAvg;
}
public static void selectionSort(int[] TestGrades, int scoreCount) {
int startScan, index, minIndex, minValue;
int[] indices = new int[scoreCount];
for (int i = 0; i < scoreCount; i++) {
indices[i] = i; // Initialize indices array
}
for (startScan = 0; startScan < (scoreCount - 1); startScan++) {
minIndex = startScan;
minValue = TestGrades[indices[startScan]]; // Use indices array for comparison
for (index = startScan + 1; index < scoreCount; index++) {
if (TestGrades[indices[index]] < minValue) { // Use indices array for comparison
minValue = TestGrades[indices[index]];
minIndex = index;
}
}
// Swap both TestGrades and indices
int temp = indices[startScan];
indices[startScan] = indices[minIndex];
indices[minIndex] = temp;
}
// Reorder TestGrades based on sorted indices
int[] sortedGrades = new int[scoreCount];
for (int i = 0; i < scoreCount; i++) {
sortedGrades[i] = TestGrades[indices[i]];
}
// Copy the sorted grades back to TestGrades array
System.arraycopy(sortedGrades, 0, TestGrades, 0, scoreCount);
}
//method to output scores and average
public static void OutputArray(int[] TestGrades, int ScoreCount, double CalcAvg) {
System.out.println("Grade Number\t\tGrade Value");
for (int i = 0; i < ScoreCount; i++) {
System.out.println((i + 1) + "\t" + "\t" + "\t" + TestGrades[i]);
}
System.out.printf("Calculated Average\t" + "%.2f%%\n", CalcAvg); // Added newline for better formatting
}
public static void OutputSortedArray(int[] TestGrades, int scoreCount) {
System.out.println("\nTable of sorted test scores");
System.out.println("Grade Number\t\tGrade Value");
for (int i = 0; i < scoreCount; i++) {
System.out.println((i + 1) + "\t" + "\t" + "\t" + TestGrades[i]);
}
}
}代码解释:
selectionSort(int[] TestGrades, int scoreCount):
OutputSortedArray(int[] TestGrades, int scoreCount):
通过修改 selectionSort() 方法并添加 OutputSortedArray() 方法,我们成功地实现了对数组中有效元素的排序,并按照特定的表格格式输出排序后的结果,同时保持了原始索引信息的对应关系。这个例子展示了如何使用 Java 数组和排序算法解决实际问题。
以上就是Java 数组排序与索引输出教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号