所以我已经在这个程序上工作了一段时间,并且我已经完成了所有工作而没有编译错误但现在我得到一个奇怪的输出,首先生病了该程序的问题。
import java.util.Scanner;
import java.util.*;
public class project3 {
private static double[] payrate;
private static String[] names;
public static void SortData(double payrate[]) {
int first;
int temp;
int i;
int j;
for (i = payrate.length - 1; i > 0; i--) {
first = 0;
for (j = 1; j <= i; j++) {
if (payrate[j] < payrate[first]) {
first = j;
}
}
temp = (int) payrate[first];
payrate[first] = payrate[i];
payrate[i] = temp;
}
}
public static void GetData() {
Scanner input = new Scanner(System.in);
System.out.println("How many names do you want to enter?");
String strNum = input.nextLine();
int num = Integer.parseInt(strNum);
int array[] = new int[num];
for (int i = 0; i < array.length; i++) {
names = new String[num];
System.out.println("enter employee's name: ");
names[i] = input.nextLine();
//while(names[i].length < 2)
//{
//System.out.println("enter valid employee's name: ");
//names[i] = input.nextLine();
//}
}
for (int j = 0; j < array.length; j++) {
payrate = new double[num];
System.out.println("enter employee's payrate: ");
payrate[j] = input.nextDouble();
while (payrate[j] > 100 || payrate[j] < 0) {
System.out.println("enter valid employee's payrate: ");
payrate[j] = input.nextDouble();
}
}
}
public static void DisplayData(double payrate[], String names[]) {
System.out.printf("Name PayRate\n");
for (int l = 0; l < names.length; l++) {
//for(int i=0;i<names.length;i++)
// {
System.out.print(names[l]);
System.out.printf("\n", payrate[l]);
//}
}
}
public static void main(String[] args) {
GetData();
SortData(payrate);
DisplayData(payrate, names);
}
}
程序假设打印出类似这样的东西
Name Payrate
Daniel 54.76
josh 73.12
kyle 12.54
但程序打印出来
Name PayRate
null
null
null
null
qt
答案 0 :(得分:1)
以下是您可以纠正的一点。
GetData()
中,您应该将names = new String[num];
放在任何地方
在循环开始之前,所以deos payrate = new double[num];
。
SortData()
中,为什么不使用double temp;
?然后你不必将payrate[first]
变成int类型。
DisplayData()
,System.out.printf("\n", payrate[l]);
显示
改变线条。我认为最好像
System.out.printf("Name\tPayRate\n");
for (int l = 0; l < names.length; l++) {
System.out.print(names[l]);
System.out.println("\t"+payrate[l]);
}
嗯,用代码解释而不是英语是eaiser。 :&#39;(
public static void SortData(double payrate[]) {
int first;
double temp;
String tempString;
int i;
int j;
for (i = payrate.length - 1; i > 0; i--) {
first = 0;
for (j = 1; j <= i; j++) {
if (payrate[j] < payrate[first]) {
first = j;
}
}
temp = payrate[first];
payrate[first] = payrate[i];
payrate[i] = temp;
tempString = names[first];
names[first] = names[i];
names[i] = tempString;
}
}