1

继续在 java.util.Scanner.next(Unknown Source) 在 java.util.Scanner.nextInt(Unknown Source) 在 java.util.Scanner.throwFor(Unknown Source) 处收到错误 java.util.InputMismatchException。 Scanner.nextInt(Unknown Source)
文件顺序:string string int

import java.util.Scanner; 
import java.io.*;

class PlayerStats 
{       
    public String name;   
    public String team;   
    public int games_ply; 
    public int goals_mde;
}

public class Program3
{
    public static void main(String[] args)
    {    

    PlayerStats[] players = new PlayerStats[100];
    int nPlayers;
    int opt;
    Scanner in = new Scanner (System.in
    nPlayers = loadPlayers (players);
    } 

    private static int loadPlayers (PlayerStats[] players)
    {   
        int nPlayers = 0;   
        try
        {   
        File file = new File ("/temp/Program3/Player.txt");
        Scanner inFile = new Scanner (file);
        do
        {
                players[ nPlayers ] = new PlayerStats();
            players[ nPlayers ].name = inFile.next();
            players[ nPlayers ].team = inFile.next();
            players[ nPlayers ].games_ply = inFile.nextInt();
            players[ nPlayers ].goals_mde = inFile.nextInt();
            ++nPlayers;
        } while ( players [nPlayers-1].goals_mde != 0);
    --nPlayers;
       }
       catch (IOException ioe)
       {
           System.out.print("\n\n\t\tFile access error!");
       nPlayers = 0;
       }
       return nPlayers;
    }
}
4

2 回答 2

0

I guess you should use ObjectOutputStream to write your serialized Players object to the file, and use ObjectInputStream(new FileInputStream(new File(players.txt))).readObject to read the object, and don't forget to cast it to Players

于 2013-12-11T07:13:29.663 回答
0

检查您的字符串是否有空格,如果是,那么您的代码将无法正常工作,.next()直到空格

然后试试这个

String line = inFile.nextLine();
String [] tokens = line.split("\s+");
players[ nPlayers ].name = tokens[0];
players[ nPlayers ].team = tokens[1];
players[ nPlayers ].games_ply = Integer.parseInt(tokens[2]);
players[ nPlayers ].goals_mde = Integer.parseInt(tokens[3]);
于 2018-04-18T04:51:47.047 回答