我创建的数组是否可以保存多个数据? 例如,当用户添加游戏时,我想显示多个游戏的总分,但是使用下面的代码,我的数组只包含最后一个输入数据。
import java.util.Scanner;
public class Assingment2
{
public static void main (String[] args)
{
String text;
String gameName;
int scores;
int timePlayed;
int i = 0;
int total = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name");
text = sc.nextLine();
System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");
while (i < 100){
text = sc.nextLine();
if (text.isEmpty()){
System.out.println("Nothing was entered. Please try again");
break;
}
if(text.equals("quit")){
break;
}
System.out.println (text);
i++;
String [] splitText = text.split(":");
if (splitText.length !=3){
System.out.println("Error please try again");
break;
}
gameName=splitText[0];
scores=Integer.parseInt(splitText[1]);
timePlayed=Integer.parseInt(splitText[2]);
System.out.println("Game: "+splitText[0]+", Score= "+splitText[1]+", Time Played= "+splitText[2]);
}
}
}
答案 0 :(得分:2)
你可以这样做。有2个名为Player
和Game
的课程。 Game
类可以是以下内容:
public class Game {
String name;
int score;
int timePlayed;
}
,Player
类可以是以下内容:
public class Player {
String playerName;
ArrayList<Game> gamesPlayed;
}
然后,在主程序中,您可以添加代码来迭代玩家,添加游戏数据,操纵游戏数据等。