我似乎无法克服这个错误。我的代码:
import java.util.*;
public class Collector {
public static void Names () {
java.util.Scanner input = new java.util.Scanner(System.in);
// Prompt the user to enter the number of students
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();
// Create arrays
String[] names = new String[numberOfStudents];
double[] scores = new double[numberOfStudents];
// Enter student name and score
for (int i = 0; i < scores.length; i++)
{
System.out.print("Enter student's name: ");
names[i] = input.next();
System.out.print("Enter student's exam score: ");
scores[i] = input.nextDouble();
System.out.println(" ");
}
}
void SortRoutine (String[] names, double[] scores) {
for (int i = scores.length - 1; i >= 1; i--)
{
// Find the maximum in the scores[0..i]
double currentMax = scores[0];
int currentMaxIndex = 0;
for (int j = 1; j <= i; j++)
{
if (currentMax < scores[j])
{
currentMax = scores[j];
currentMaxIndex = j;
}
}
//arrange values as necessary
if (currentMaxIndex != i)
{
scores[currentMaxIndex] = scores[i];
scores[i] = currentMax;
String temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
}
}
// Print student data
System.out.println(" ");
System.out.println("***** Student Scores Sorted High to Low *****");
System.out.println(" ");
for (int i = scores.length - 1; i >= 0; i--)
{
System.out.println(names[i] + "\t" + scores[i] + "\t");
}
System.out.println(" ");
}
}
主要方法:
import java.util.*;
import java.util.Arrays;
public class NameCollector {
public static void main(String[] args) {
Collector collect = new Collector();
collect.Names();
collect.SortRoutine();
}
}
如果我从Collector类的第28行删除参数,我会得到cannot find symbol errors
。我相信这意味着Jcreator无法找到数组值。我如何才能使第一个方法中定义的数组值对第二个方法可见?如果我在第28行留下参数,则错误信息为:
C:\Users\Dark Prince\Documents\JCreator LE\MyProjects\NameCollector\src\NameCollector.java:16: error: method SortRoutine in class Collector cannot be applied to given types;
collect.SortRoutine();
^
required: String[],double[]
found: no arguments
reason: actual and formal argument lists differ in length
1 error
流程已完成。
我在想我不应该使用这些参数并使其成为排序方法可以看到的数组值,但实际上我只是希望这个有用的东西。
答案 0 :(得分:0)
您问:如何将第一种方法中定义的数组值显示在第二种方法中?
有很多方法可以做到这一点。这是做到这一点的一种方式(可能不是最好的):
您可以将数组转换为Collector类中的静态实例成员,如下所示:
public class Collector {
static String[] names;
static double[] scores;
public static void Names () {
然后当你在Names方法中创建数组时,你会这样做:
// Create arrays
names = new String[numberOfStudents];
scores = new double[numberOfStudents];
最后,您从:
更改SortRoutine的方法签名void SortRoutine (String[] names, double[] scores)
到
void SortRoutine ()