我是Java新手(一般編碼),所以我很抱歉提前發現錯誤。我相信可能有更簡單的方法來做到這一點,但我無法弄清楚。 我覺得我也犯了一個非常明顯的錯誤。並排打印一維和二維數組
這是我一直在問的事:
編寫一個程序,以隨機順序和 他/她相應的3分項目的成績將輸入的10學生姓名。這些數據將被讀取爲 爲2個單獨的數組:一個字符串數組以保存名稱,以及一個數字的二維數組來保存分數。您可以從鍵盤或文本文件輸入 數據。
以表格形式輸出輸入數據。
使用選擇排序,按字母順序重新排列隨機學生姓名 。按照排序順序,相應的分數顯然需要 。 以 表格形式輸出排序後的名稱和分數。
使用二進制搜索,您的程序將允許用戶輸入名稱。 您的程序將輸出名稱及其對應的3個項目 分數。
對於3個項目中的每一個,輸出 得分最高的學生姓名。
粗體部分是卡住的地方。我編譯並正常運行,但是在打印表格時,例如只輸入最後一組輸入的3個數字(是的,格式化需要進行處理,以便它是一個表格,這只是一個臨時格式直到我解決了這個問題) This is what I get.其餘的名字被切斷了,但它們都打印了相同的分數。
import java.util.Scanner;
/**Write a program that will input 10 students names
* in random order and their corresponding 3 project scores.
* Data will be read into 2 separate arrays: an array of strings
* for the names and a 2D array for the scores.
* Output input data in table form
*For each of the 3 projects, output the name of the student(s) who scored
the highest mark.
**/
public class NameAndGrades
{
public static void main (String[] args)
{
//Scanner object to allow user input
Scanner scnr = new Scanner(System.in);
//This array will store the names of the students
String[] names = new String[10];
//This 2D array will store the 3 project scores
int[][] scores = new int [10][3];
//Ask user to input the student names
System.out.println("Enter the 10 student names: ");
for (int index = 0; index < 10; index++)
{
System.out.print("Student " + (index +1) + ": ");
names[index] = scnr.nextLine();
}
selectionSort(names);
//Will print the names alphabetically
//THIS WILL BE DELETED LATER, IT WAS JUST TO CHECK IF IT DID ITS JOB
System.out.println("The students' names in alphabetical order: ");
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i]);
}
//Ask user to enter the corresponding project scores
System.out.println("Enter the 3 project "
+ "scores for each student: ");
for (int row = 0; row < scores.length; row++)
{
for (int i = 0; i < names.length; i++)
{
for (int col = 0; col < scores[row].length; col++)
{
System.out.print(names[i] + " Test "
+ (col +1) + ": ");
scores[row][col] = scnr.nextInt();
}
}
break;
}
//PRINT NAMES AND SCORES SIDE BY SIDE
//MAKE TABLE HEADING HERE
for (int row = 0; row < scores.length; row++)
{
for (int i = 0; i < names.length; i++)
{
System.out.println(names[i] + " grades: ");
for (int col = 0; col < scores[row].length; col++)
{
System.out.print(scores[row][col] + " ");
}
System.out.println();
}break;
}
}
/**Selection sort method made to sort the student names in
* alphabetical order.
@param names names of students
@return the names organized alphabetically
**/
public static String[] selectionSort(String[] names)
{
for (int index = 0; index < names.length - 1; ++index)
{
int minIndex = index;
for (int j = index + 1; j < names.length; ++j)
{
if (names[j].compareTo(names[minIndex]) < 0)
{
minIndex = j;
}
}
String temp = names[index];
names[index] = names[minIndex];
names[minIndex] = temp;
}
return (names);
}
}
我該如何編輯這樣才能讓每個學生都有正確的分數? 預先感謝您的幫助!
表應該是什麼樣子? –
完成此操作的一種方法不是返回一個字符串數組,而是讓您的'selectionSort()'直接對數組執行操作並讓int數組模仿對字符串數組執行的操作 –