내 임무는 다음과 같습니다어떻게 평균을 arrayList에 넣을 수 있으며, 입력 파일의 점수를 자신의 arrayList에 저장하려면 어떻게해야합니까?
: 여기79 84 90
92 78 85
90 88 92
98 94 92
88 78 84
내가 할당을 완료하기 위해 쓴 코드입니다 :
Suppose there is a file called Numbers.txt that contains a number of lines of data. Each line contains three integers. Write a program that reads each line of data from the file and places the average of the three integers into an ArrayList of integers. After all the data has been read and the averages calculated your program should write the averages to a file called Output.out
입력 파일에 테스트 데이터는 다음과 같은 포함
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class MeanCalc
{
public static void main(String[] args)
{
try
(FileReader reader = new FileReader("Numbers.txt");
Scanner in = new Scanner(reader);
FileWriter writer = new FileWriter("Output.txt");
PrintWriter out = new PrintWriter(writer))
{
ArrayList<String> scores = new ArrayList<String>();
ArrayList<Integer> avgs = new ArrayList<Integer>();
while(in.hasNextLine())
{
String nextLine = in.nextLine();
StringTokenizer st = new StringTokenizer(nextLine);
if(st.countTokens() == 3)
{
String score1 = st.nextToken();
String score2 = st.nextToken();
String score3 = st.nextToken();
try
{
int s1 = Integer.parseInt(score1);
int s2 = Integer.parseInt(score2);
int s3 = Integer.parseInt(score3);
scores.add(score1);
scores.add(score2);
scores.add(score3);
avgs.add((s1 + s2 + s3)/3);
}
catch(NumberFormatException e)
{System.out.println("Invalid data: " + nextLine);}
}
}
if(scores.size() > 0)
{
calcMean(avgs);
for(int i = 0; i < scores.size(); i++)
out.printf("%-20s %5.2d\n", scores.get(i), avgs.get(i));
}
}
catch(IOException e)
{
System.out.println("Error processing file: " + e);
System.exit(1);
}
}
public static double calcMean(ArrayList<Integer> table)
{
double total = 0;
for(int i = 0; i < table.size(); ++i)
total += table.get(i);
return total/table.size();
}
}
내가 작성한 코드가 제대로 작동하지 않습니다. 다음 오류가 발생합니다.
Exception in thread "main" java.util.IllegalFormatPrecisionException: 2
at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2984)
at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2729)
at java.util.Formatter.parse(Formatter.java:2560)
at java.util.Formatter.format(Formatter.java:2501)
at java.io.PrintWriter.format(PrintWriter.java:905)
at java.io.PrintWriter.printf(PrintWriter.java:804)
at MeanCalc.main(MeanCalc.java:51)
은 내가 라인 (51)과 함께 만들고있어 어떤 실수 확실하지 않다, 나는 누군가가 내 프로그램
은 double의 ArrayList가 평균이 아니어야합니다. 그렇지 않으면 일부 계산에서 정밀도가 떨어질 수 있습니까? –
할당은 특별히 각 행에있는 3 개의 정수의 평균을 정수의 arrayList에 두도록 요청합니다. –
그게 요구된다면 나는 너의 편이다.). –