A.hussain
A.hussain

Reputation: 37

It is possible to store multiple data in arrays

Is it possible for the array I have created to hold multiple data? For example when a user adds a game I want to display the total score for multiple games, however with the below code, my array only contains the last input data.

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

Upvotes: 1

Views: 805

Answers (1)

Pubudu
Pubudu

Reputation: 994

You can do something like this. Have 2 classes called Player and Game. The Game class can be something like the following:

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

and the Player class can be something like the following:

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

Then, in the main program, you can add code to iterate through the players, add game data, manipulate game data etc.

Upvotes: 2

Related Questions