继续在java.util.Scanner.next(未知来源)的java.util.Scanner.throwFor(未知来源)获取java.util.InputMismatchException java.util.Scanner.nextInt(未知来源)java .util.Scanner.nextInt(未知来源)
文件顺序:字符串字符串int 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;
}
}
答案 0 :(得分:0)
我猜您应该使用ObjectOutputStream
将serialized
玩家对象写入文件,并使用ObjectInputStream(new FileInputStream(new File(players.txt))).readObject
来阅读对象,不要忘记将其投射到玩家< / p>
答案 1 :(得分: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]);