如何使用循环在数组中存储名称?

时间:2017-01-18 22:43:49

标签: java arrays loops

我试图编写一个程序,提示用户输入游戏玩家的数量,游戏玩家'名字,他们的分数,并打印他们的分数'按其分数的降序排列。

我需要使用数组作为名称和分数。不幸的是,这就是我的全部。

示例输出

Enter the number of players: n
Enter the name of the player: Ash
Enter the player's score: 1200
Enter the name of the player: Brock
Enter the player's score: 900
Enter the name of the player: Misty
Enter the player's score: 1300
Misty     1300.0
Ash       1200.0
Brock     900.0
import java. util.*;


public class HomeworkAssignment12 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the number of game players: ");
        int numOfPlayers = input.nextInt();
        String[] names = new String[numOfPlayers];
        double[] scores = new double[numOfPlayers];

        //Trying to store the names the user inputs into the names[] array  
        for ( int i = 0; i < names.length; i++) {
            int index = i;
            System.out.println("Enter a game players name: ");
            names[index] = input.nextLine();
            System.out.println("Enter the player's score: ");
            scores[index] = input.nextDouble();

            //used to check what the loop is doing each iteration
            System.out.println(i);

        }//end for

    }//end main

}//end class

1 个答案:

答案 0 :(得分:0)

你几乎在那里,以下代码扩展了你的伟大尝试。至于你如何使用索引将名称添加到数组中的问题?您只需使用i中的变量for-loop

(我遗漏了如何以您想要的格式打印两个数组中的值作为练习):

import java.util.Scanner;
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter the number of game players: ");
    int numOfPlayers = scanner.nextInt();
    String[] names = new String[numOfPlayers];
    double[] scores = new double[numOfPlayers];

    for (int i=0; i<names.length; i++){
      System.out.print("Enter a players name: ");
      String name = scanner.next();
      names[i] = name;
      System.out.print("Enter " + name  +"\'s score: ");
      while(scanner.hasNext()) {
        if(scanner.hasNextDouble()) {
          double score = scanner.nextDouble();
          scores[i] = score;
          break;
        } else {
          System.out.println("ERROR: Invalid Input");
          System.out.print("Enter " + name  +"\'s score: ");
          scanner.next();
        }
      }
    }
    System.out.println("The names array: " + Arrays.toString(names));
    System.out.println("The scores array: " + Arrays.toString(scores));
  }
}

示例用法:

Enter the number of game players:  2
Enter a players name:  Max
Enter Max's score:  3
Enter a players name:  John
Enter John's score:  6
The names array: [Max, John]
The scores array: [3.0, 6.0]

试试here!