【发布时间】:2017-09-09 01:51:44
【问题描述】:
我目前正在为我的编程课做作业,但我不知道为什么我的输出出错了。
我们应该“打印人口与上一年的“差异”。(当然,列表中的第一年这个值是空白的。) 使用格式控件打印年份、人口值和与上一年的差异的值。 "
我的老师给了我们输出应该是什么样子的:
期望的输出:
但我不断得到这个:
我的输出:
这是我的代码:
import java.util.Scanner;
import java.io.*;
public class AssignmentOne
{
public static void main(String[] args) throws IOException
{
// Array Version
ArrayVersion();
System.out.println("Finished Array Version of Assignment");
}
// Method for ArrayVersion
public static void ArrayVersion() throws IOException
{
// Year as variables
int year = 1950;
final int ARRAY_SIZE = 41;
// Array to use for Population data
int[] population = new int[40];
// Call the method to get data into array
population = getDataFromFile("USPopulation.txt");
if(population == null)
{
System.out.println("Error: Population did not load");
return;
}
// Output
System.out.println("This is the Simple Array Version of \nPopulation Data US");
System.out.println("\nYear \tPopulation \tDifference");
System.out.println("");
System.out.printf("%d \t%,d,000\n", year, population[0]);
for(int i = 1; i < population.length; i++)
{
System.out.printf("%d \t%,d,000 \t%,d,000 \n", ++year, population[i], Math.abs(population[i] - population[++i]));
}
// Calculating the average + displaying it
int sum = 0;
for(int g = 0; g < population.length; g++)
{
sum += population[g];
}
int average;
average = sum / population.length;
System.out.println("Average:" + average);
}
// Method to get data from specified "filename" into an array of ints
public static int[] getDataFromFile(String USPopulation) throws IOException
{
// Array to use for Population data
// Opening file
File file = new File("E:/Programming 2/Assignment 1/src/USPopulation.txt");
Scanner inputFile = new Scanner(file);
int fileSize = 0;
while(inputFile.hasNext())
{
inputFile.nextInt();
fileSize++;
}
Scanner input2 = new Scanner(file);
int[] fileData = new int[fileSize];
for(int i = 0; i < fileSize; i++)
{
fileData[i] = input2.nextInt();
}
// System.out.println(fileData[40]);
// return the array fileData
return fileData;
}
【问题讨论】:
标签: java arrays methods output