[英]How do I add user input to parallel arrays in java?
这是我现在拥有的代码,完全被砍掉了。 我在尝试让用户输入一个字符串和两个双精度字进入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
方法。 您可能也想更改其实现。
希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.