这是我现在拥有的代码,它是完全屠宰的。我有问题尝试允许字符串的用户输入和两个双打进入3个并行数组,然后保存到.txt文件。我不知道有人可以帮助我吗?
public static void addGames(int i, String[] array1, double[] array2,
double[] array3, int arrayLength, Scanner keyboard) throws IOException
{
String newName;
double newPrice;
double newRating;
if(i < arrayLength)
{
System.out.println("Please enter another game name: ");
newName = keyboard.next();
array1[i] = newName;
System.out.println("Please enter another game price: ");
newPrice = keyboard.nextDouble();
array2[i] = newPrice;
System.out.println("Please enter another game rating: ");
newRating = keyboard.nextDouble();
array3[i] = newRating;
i++;
}
else
{
System.out.println("There is no more room to store games: ");
}
PrintWriter gamerOut = new PrintWriter("Project1_VideoGames.txt");
while(i < array1.length)
{
gamerOut.write(array1[i]);
gamerOut.add(array2[i]);
gamerOut.add(array3[i]);
i++;
}
gamerOut.close();
}
for (int j = 0; j < i; ++j) {
gamerOut.println(array1[j] + "t" + array2[j] + "t" + array3[j]);
无需说名字对我来说太富有想象力。做一个
public class Game {
String name;
double price;
double rating;
}
检查是否是您想要的。
我没有3个阵列,而是将所有内容都封装在Game
类中。
public class Game {
private String name;
private double price;
private double rating;
public Game(String name, double price, double rating){
this.name = name;
this.price = price;
this.rating = rating;
}
@Override
public String toString(){
String ret = "";
ret = ret + name + " / " + price + " / " + rating;
return ret;
}
}
这就是我为您的addGames
函数所提供的。现在只需1个参数:您要在文件中写的游戏数。
public static void addGames(int gamesNumber) throws IOException
{
int i = 0;
String newName;
double newPrice, newRating;
Scanner keyboard = new Scanner(System.in);
ArrayList<Game> array = new ArrayList<Game>();
while(i < gamesNumber)
{
System.out.println("Please enter another game name: ");
newName = keyboard.next();
System.out.println("Please enter another game price: ");
newPrice = keyboard.nextDouble();
System.out.println("Please enter another game rating: ");
newRating = keyboard.nextDouble();
System.out.println();
Game game = new Game(newName, newPrice, newRating);
array.add(game);
i++;
}
System.out.println("There is no more room to store games. ");
PrintWriter gamerOut = new PrintWriter("Project1_VideoGames.txt");
i = 0;
while(i < array.size())
{
gamerOut.println(array.get(i));
i++;
}
gamerOut.close();
System.out.println("The games have been written in the file");
}
您可能想在阅读用户输入或处理FileWriter
的异常时处理一些错误,但我将其留给您。
另外,我更改为PrintWriter#println
方法而不是PrintWriter#write
,并在Game
类中覆盖toString
方法。您可能也需要更改其实现。
希望这有所帮助。