Java Setters / Getters - Как мне сохранить мою строку в массиве в моем методе? - PullRequest
0 голосов
/ 19 октября 2019

Я пытаюсь преобразовать свой исходный код как метод. Однако мои входные данные не сохраняются в массиве, поскольку я пытался их отобразить. Пожалуйста, совет!

Оригинал (работает нормально):

    private static Scanner sc;
    
    private static GameScore readGameScore() {
        System.out.println("- Enter Score Data -");
        
        //declare a GameScore variable
        Scanner sc = new Scanner(System.in);
        String username = "";
        int gameId = 0;
        int score = 0;
        
        //asking the user to re-enter the name while not valid.        
        while (true) {
            System.out.println("Enter username");
            username = sc.next();
            if (username.trim().length() == 0) {
                System.out.println("Invalid username. Please re-enters");
            } 
            
            else {
                break;
            }
        }

public static void main(String[] args) {
        scanner = new Scanner(System.in);
        final int CAPACITY = 50;
        GameScore[] gameScoreArray = new GameScore[0];
        List<GameScore> gameScoreList = new ArrayList<>();
        int numScores = 0;
        numScores = Math.min(numScores, CAPACITY);
        
        
        GameScore newGameScore = readGameScore();
       gameScoreList.add(newGameScore);
       gameScoreArray = gameScoreList.toArray(new GameScore[gameScoreList.size()]);
       break;
    }

Преобразование в метод addGameScore (Это не работает так, как я хотел. Я пытался добавить некоторые входные данные, но он продолжал выглядеть как «Коллекция заполнена. s "):

private static int addGameScore(GameScore[] scores, int numScores, GameScore newGameScore) {
    
       if (numScores < scores.length) { 
              
            scores[numScores] = newGameScore;
            
            numScores += 1;
        }
        
        else {
            System.out.println("The collection is full.");   
        }
        
        return numScores;
    }

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        final int CAPACITY = 50;
        GameScore[] gameScoreArray = new GameScore[0];
        List<GameScore> gameScoreList = new ArrayList<>();
        int numScores = 0;
        numScores = Math.min(numScores, CAPACITY);

        addGameScore(gameScoreArray, numScores, newGameScore);
    
}
...