首先是一些背景:
主要方法将通过执行以下操作来驱动您的程序: •创建一个阵列以容纳所有单个高尔夫球手和标准杆分数(类型为Golfer [])。 •提示用户输入包含Par分数以及玩家姓名和分数的数据文件。输入文件的格式应如下所示:
参数,3,4,4,3,4,3,5,3,4
乔治,3,3,4,3,4,2,3,3,4 保罗,4,5,4,3,6,3,4,3,5Ringo,3,3,4,3,4,2,4,3,4
John,4,4,4,3,4,2,5,3,4
这是我到目前为止所做的:
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
boolean tryAgain;
do
{
Scanner console = new Scanner( System.in );
System.out.print( "Please enter a file name to read: " );
String inFile = console.next();
tryAgain = false;
try
{
File file = new File( inFile );
Scanner tokens = new Scanner( file );
int data[][];
String str = "";
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 10; j++)
{
int value = tokens.nextInt();
}
System.out.printf("\n");
}
tokens.close();
String people [] = str.split(",");
Golfer golfers = new Golfer(null, null);
}
catch (IOException e)
{
System.out.printf("Error opening file %s, %s\n", inFile, e);
tryAgain = true;
}
}
while (tryAgain);
}
我不确定如何正确使用嵌套for循环来拉取数据并将其存储在数组中,因为有两种数据类型。而且......我猜任何有关如何在我的高尔夫球手课程中存储信息的建议都不会受到伤害。我是初学者,所以应该避免任何复杂的技术。
任何建议都将不胜感激。 谢谢!
答案 0 :(得分:2)
在这种情况下,需要创建一个时间来保存单行中的所有数据,例如名称和数组,以保存该特定高尔夫球手的所有分数。
while(tokens.hasNext()) {
String input = token.nextLine();
String [] splitGolfer = input.split(",");
Golfer newGolfer = new Golfer();
newGolfer.name = splitGolfer[0];
ArrayList<Integer> scores = new ArrayList<Integer>();
for(int i= 1; i < splitgolfer.length; i++) {
scores.add(Integer.valueOf(splitGolfer[i]);
}
newGolfer.scores = scores;
高尔夫球手班:
String name;
ArrayList<Integer> scores;
答案 1 :(得分:0)
这是适合您的解决方案。根据您的要求更改变量,文件名和目录。 如果文件中的任何行格式与您上面提到的格式不同(播放器名称后跟分数),它将抛出异常。
import java.util.*;
import java.io.*;
public class Golfer
{
//arraylist of all lines from given files (players data).
ArrayList<String> theData = new ArrayList<String>();
private String playerName;
private ArrayList<Integer> parScores;
//you must read each line in the golder file and send it individually to this method.
public Golfer() throws IOException
{
String fileName = "players.txt";
theData = readFile(fileName);
for (String s : theData)
{
getPlayerData(s);
}
}
public void getPlayerData(String data)
{
String[] list = data.split(",");
playerName = list[0];
parScores = new ArrayList<Integer>();
for( int i = 1; i < list.length; i++)
{
parScores.add(Integer.parseInt(list[i]));
}
}
//This method will read your data file and will return arraylist (one array for each player).
public ArrayList<String> readFile(String fileName) throws IOException
{
ArrayList<String> data = new ArrayList<String>();
//don't forget to add directory name here if you have, because we are only passing filename, not directory.
BufferedReader in = new BufferedReader(new FileReader(fileName));
String temp = in.readLine();
while (temp != null)
{
data.add(temp);
temp = in.readLine();
}
in.close();
return data;
}
}