所以我已经解决了这个问题一段时间了,它是一段代码,用来显示已经从用户收集和分类的数据。首先发布代码而不是发布错误。
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[])
{
int locationsum = 0;
for (int l=1; l<=names.length; l++)
{
locationsum = 0;
locationsum+=payrate[l];
}
for(int i=0;i<names.length;i++)
{
System.out.print(names[i]);
System.out.printf("%6d\n", locationsum);
}
}
public static void main(String[] args)
{
GetData();
SortData(payrate);
DisplayData(payrate,names);
}
}
我无法找到一种从阵列中打印出所有内容的方法,并且通过这种方式它不断给我这个。我得到的错误是:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at project3.DisplayData(project3.java:77)
at project3.main(project3.java:94)
答案 0 :(得分:4)
在DisplayData
方法中,您需要重复(包括)names.length
:
for (int l=1; l<=names.length; l++)
数组索引从零开始,这意味着第一个索引始终为零,最后一个索引为length-1
。尝试访问length
处的索引将为您提供ArrayOutOfBoundsException,因为任何数组都不存在该索引。
答案 1 :(得分:-1)
将for (int l = 1; l <= names.length; l++)
更改为for (int l = 1; l < names.length; l++)
。