1

次のようにフォーマットされたテキストファイルがあります。

Han Solo:1000
Harry:100
Ron:10
Yoda:0

Han Soloプレイヤーの名前 ( ) とスコア ( 1000) を属性として格納するオブジェクトの arrayList を作成する必要があります。ファイルを1行ずつ読み取り、文字列を分割して目的の属性を取得することにより、このarrayListを作成できるようにしたいと考えています。オブジェクトを使用してみましたScannerが、うまくいきませんでした。これに関するヘルプは大歓迎です、ありがとう。

4

6 に答える 6

1

You can have a Player class like this:-

class Player { // Class which holds the player data
    private String name;
    private int score;

    public Player(String name, int score) {
        this.name = name;
        this.score = score;
    }

    // Getters & Setters
    // Overrride toString()  - I did this. Its optional though.
}

and you can parse your file which contains the data like this:-

List<Player> players = new ArrayList<Player>();
try {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); // I used BufferedReader instead of a Scanner
    String line = null;
    while ((line = br.readLine()) != null) {
        String[] values = line.split(":"); // Split on ":"
        players.add(new Player(values[0], Integer.parseInt(values[1]))); // Create a new Player object with the values extract and add it to the list
    }
} catch (IOException ioe) {
    // Exception Handling
}
System.out.println(players); // Just printing the list. toString() method of Player class is called.
于 2013-09-18T11:15:28.303 に答える
1

オブジェクトがある場合:

public class User
{
    private String name;
    private int score;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public int getScore()
    {
        return score;
    }

    public void setScore(int score)
    {
        this.score = score;
    }

}

ファイルから読み取る Reader クラスを作成します。

public class Reader
{
    public static void main(String[] args)
    {
        List<User> list = new ArrayList<User>();
        File file = new File("test.txt");
        BufferedReader reader = null;
        try
        {
            reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null)
            {
                String[] splitedString = line.split(":");
                User user = new User();
                user.setName(splitedString[0]);
                user.setScore(Integer.parseInt(splitedString[1]));
                list.add(user);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        for (User user : list)
        {
            System.out.println(user.getName()+" "+user.getScore());
        }
    }
}

出力は次のようになります。

ハン・ソロ 1000 ハリー 100 ロン 10 ヨーダ 0

于 2013-09-18T11:16:30.053 に答える
0

String 型の名前とint 型のスコアの2 つのデータ メンバーで構成されるPlayerというクラスがあるとします。

List<Player> players=new ArrayList<Player>();
        BufferedReader br=null;
        try{
            br=new BufferedReader(new FileReader("filename"));
            String record;
            String arr[];
            while((record=br.readLine())!=null){
                arr=record.split(":");
                //Player instantiated through two-argument constructor
                players.add(new Player(arr[0], Integer.parseInt(arr[1])));
            }
        } catch (FileNotFoundException e) {             
            e.printStackTrace();
        } catch (IOException e) {               
            e.printStackTrace();
        }
        finally{
            if(br!=null)
                try {
                    br.close();
                } catch (IOException e1) {                      
                    e1.printStackTrace();
                }
        }
于 2013-09-18T11:34:32.323 に答える
0

小さなファイル (8kb 未満) の場合は、これを使用できます。

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class NameScoreReader {

List<Player> readFile(final String fileName) throws IOException
{
    final List<Player> retval = new ArrayList<Player>();

    final Path path = Paths.get(fileName);
    final List<String> source = Files.readAllLines(path, StandardCharsets.UTF_8);
    for (final String line : source) {
        final String[] array = line.split(":");
        if (array.length == 2) {
            retval.add(new Player(array[0], Integer.parseInt(array[1])));
        } else {
            System.out.println("Invalid format: " + array);
        }
    }
    return retval;
}


class Player {

    protected Player(final String pName, final int pScore) {
        super();
        this.name = pName;
        this.score = pScore;
    }

    private String name;

    private int score;

    public String getName()
    {
        return this.name;
    }
    public void setName(final String name)
    {
        this.name = name;
    }

    public int getScore()
    {
        return this.score;
    }
    public void setScore(final int score)
    {
        this.score = score;
    }

}

}

于 2013-09-18T11:38:51.910 に答える
0

ファイルを読み取り、結果に適用できる文字列と分割関数に変換します。

public static String getStringFromFile(String fileName) {
        BufferedReader reader;
        String str = "";
        try {
            reader = new BufferedReader(new FileReader(fileName));
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append("\n");
            }
                str = stringBuilder.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }

    public static void main(String[] args) {
        String stringFromText = getStringFromFile("C:/DBMT/data.txt");
        //Split and other logic goes here
    }
于 2013-09-18T11:41:49.013 に答える