gpt4 book ai didi

java - 可以在数组中存储多个数据

转载 作者:行者123 更新时间:2023-11-30 03:08:10 26 4
gpt4 key购买 nike

我创建的数组可以容纳多个数据吗?例如,当用户添加游戏时,我想显示多个游戏的总得分,但是使用下面的代码,我的数组仅包含最后的输入数据。

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]);
}
}
}

最佳答案

你可以做这样的事情。有 2 个类,名为 PlayerGameGame 类可以类似于以下内容:

public class Game {
String name;
int score;
int timePlayed;
}

Player 类可以如下所示:

public class Player {
String playerName;
ArrayList<Game> gamesPlayed;
}

然后,在主程序中,您可以添加代码来迭代玩家、添加游戏数据、操作游戏数据等。

关于java - 可以在数组中存储多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34229048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com