我需要编写一个程序来从文件中读取(所有行星的)地心引力的数据列表,并计算每个行星上我的体重(以磅为单位)。我需要在格式化表中显示数据。
这是我到目前为止的内容:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.PrintWriter;
public class WeightOnPlanetsV1
{
public static void printHeading(){
System.out.println(" My Weight on the Planets ");
System.out.printf("%9s%13s%15s", "Planet", "Gravity", "Weight(lbs)");
System.out.println("\n ------------------------------------");
}
public static double [] readFile() throws IOException{
double[] gravity = new double [7];
Scanner inFile = new Scanner(new File("gravitydata.txt"));
int count = 0;
while (inFile.hasNext()){
double temp = inFile.nextDouble();
gravity[count] = temp;
count++;
}
inFile.close();
return gravity;
}
public static double[]calculateWeight()throws IOException{
double[] gravity = new double [7];
readFile();
double[] mass = new double[7];
double[] weight = new double[7];
for (int a = 0; a < 9; a++){
mass[a] = (110*433.59237)/(gravity[a]);
weight[a] = (mass[a]*gravity[a]);
a++;
}
return weight;
}
public static void main (String[] args)throws IOException{
double[] gravity = new double [7];
printHeading();
String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
calculateWeight();
double [] weight = calculateWeight();
for(int y = 0; y < 9 ; y++)
{
System.out.printf("%-11s", names[y]);
System.out.printf("%13.2f", gravity[y]);
System.out.printf("%20.2f\n",weight[y]);
}
}
}
当我运行代码时,唯一显示的是标头,并且出现数组越界错误。文件中有8个行星重力,所以我不确定到底是哪里出了问题。我尝试过编辑各种各样的东西,但是我无法再做任何其他事情了。如果有人可以帮助我弄清楚代码出了什么问题,我将不胜感激。
最佳答案
您需要修复一些问题。我在代码中添加了注释
public static double [] readFile() throws IOException{
double[] gravity = new double [8]; //size 8 instead of 7
Scanner inFile = new Scanner(new File("gravitydata.txt"));
int count = 0;
while (inFile.hasNext()){
double temp = inFile.nextDouble();
gravity[count] = temp;
count++;
}
inFile.close();
return gravity;
}
public static double[]calculateWeight(double [] gravity)throws IOException{
double[] mass = new double[8]; //size 8 instead of 7
double[] weight = new double[8]; //size 8 instead of 7
for (int a = 0; a < 8; a++){ //loop 8 times, not 9
mass[a] = (110*433.59237)/(gravity[a]);
weight[a] = (mass[a]*gravity[a]);
//a++; you don't need to increment a here, since it's incremented in the for loop
}
return weight;
}
public static void main (String[] args)throws IOException{
printHeading();
String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
//calculateWeight(); no need to call it twice
double [] gravity = readFile();
double [] weight = calculateWeight(gravity);
for(int y = 0; y < 8; y++)//loop 8 times, not 9
{
System.out.printf("%-11s", names[y]);
System.out.printf("%13.2f", gravity[y]);
System.out.printf("%20.2f\n",weight[y]);
}
}