搜索&从并行阵列显示信息

时间:2017-05-12 02:14:16

标签: java arrays

这里只是另一个需要帮助解决编码困境的新手。我试图创建的程序是一个小型数据库,必须使用三个并行数组(userNumber,player和highScore)。目的是用户应在提示符下输入用户号码,程序将显示该人员的信息。如果输入的数字不存在,那么程序应向他们显示他们输入的数字,并让他们重新输入用户编号,直到输入正确的数字为止。
我现在遇到的问题是程序不接受除阵列中第一个用户号码之外的任何用户号码,无论它是否是阵列列表中的有效号码。此外,错误消息仅显示第一个"错误"无论多少次"错误"号码输入。
简而言之,我想正确的问题是:
1.)为了让程序只返回与输入的userNumber对应的数组条目的信息,我应该更改什么?
2.)如何更改以使每条错误消息显示"不正确"刚输入的号码?
这是我的代码:

import java.util.Scanner;


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

        int[] userNumber = new int[5];
        String[] player = new String[5];
        Double[] highScore = new Double[5];

        userNumber[0]= 1;
        userNumber[1]= 2;
        userNumber[2]= 3;
        userNumber[3]= 4;
        userNumber[4]= 5;
        player[0]= "Morpheus";
        player[1]= "Neo";
        player[2]= "Cereal Killer";
        player[3]= "Crash Override";
        player[4]= "Acid Burn";
        highScore[0]= 853797.67;
        highScore[1]= 999999.99;
        highScore[2]= 15097.34;
        highScore[3]= 864513.16;
        highScore[4]= 543188.68;

        System.out.print("Enter User# ");
        int scan= input.nextInt();
        int i=0;

        while (scan!=userNumber[i])
        {
            System.out.printf("Error #%s Is Unknown User", scan);
            System.out.print("Enter User# ");
            scan=input.nextInt();
        }
        System.out.printf("%s, user# %s, has a high score of: %s", player[i], userNumber[i], highScore[i]);

    }
}

3 个答案:

答案 0 :(得分:0)

您没有使用输入的值 - 请考虑

        while (scan < userNumber[0] || scan > userNumber[4])
        {
            System.out.printf("Error #%s Is Unknown User", scan);
            System.out.print("Enter User# ");
            scan=input.nextInt();
        }
        // now use the value
        System.out.printf("%s, user# %s, has a high score of: %s",
                    player[scan-1], userNumber[scan-1], highScore[scan-1]);

当然,您应该loop通过userNumber数组检查数字是否存在。实际上,这样的解决方案需要您创建包含此信息的单个obejct,然后拥有这些对象的Listarray

答案 1 :(得分:0)

您应该考虑为您的用户使用HashMap而不是数组。否则,每次都必须遍历整个数组以查找用户是否存在。

Map<Integer, Integer> userMap = new HashMap<>();

// map user numbers to associative array indexes.
userMap.put(1, 0);
userMap.put(2, 1);
userMap.put(3, 2);
userMap.put(4, 3);
userMap.put(5, 4);

player[0]= "Morpheus";
player[1]= "Neo";
player[2]= "Cereal Killer";
player[3]= "Crash Override";
player[4]= "Acid Burn";
highScore[0]= 853797.67;
highScore[1]= 999999.99;
highScore[2]= 15097.34;
highScore[3]= 864513.16;
highScore[4]= 543188.68;

System.out.print("Enter User# ");
int scan= input.nextInt();

// loop until the user actually exists
while (!userMap.containsKey(scan))
{
    System.out.printf("Error #%s Is Unknown User", scan);
    System.out.println();
    System.out.println("Enter User# ");
    scan=input.nextInt();

}

// get the index for the user
int lookup = userMap.get(scan);

System.out.printf("%s, user# %s, has a high score of: %s", player[lookup], scan, highScore[lookup]);

注意 使用此方法的另一个好处是您的用户号码不必按顺序排列。

例如,您可以使用以下映射,代码仍然有效:

userMap.put(1, 0);
userMap.put(2, 1);
userMap.put(9, 2); // user # 9 can map to index 2.
userMap.put(4, 3);
userMap.put(5, 4);

根据@ScaryWombat,创建一个Player类是理想的,这样你就不必使用关联数组并使你的程序更加OO。

示例

class Player
{
   private int id = 0;
   private String name;
   private Double score = 0.0;

   public Player (int id, String name, double score)
   {
       this.id = id;
       this.name = name;
       this.score = score;
   }

   @Override
   public String toString()
   {
       return String.format("%s, user# %s, has a high score of: %s", name, id, score);
   }
}

然后,您可以为玩家创建一个整数的HashMap

Map<Integer, Player> userMap = new HashMap<>();

userMap.put(1, new Player(1, "Morpheus", 853797.67));
userMap.put(2, new Player(2, "Neo", 999999.99));
userMap.put(3, new Player(3, "Cereal Killer", 15097.34));
userMap.put(4, new Player(4, "Crash Override", 864513.16));
userMap.put(5, new Player(5, "Acid Burn", 543188.68));

现在,您可以像这样查看播放器:

// get the player object for the user id
Player p = userMap.get(scan);

// print out the player like this since it has a toString()
System.out.println(p);

答案 2 :(得分:0)

我证明了另一个使用数组的答案,因为您的要求是使用并行数组。请查看代码中的所有注释。我已经添加了错误检查,因此程序不会退出也不会进入无效状态。

这里的关键是每次用户输入潜在的用户号码时都必须遍历整个阵列。

import javax.swing.JOptionPane;

public class HighScoreSearch
{
    // You need an indicator for an invalid user in the case where
    // you don't use all array positions
    private static final int INVALID_USER_NUM = -1;

    public static void main(String[] args)
    {
        // consider renaming this int to something like userNumber (scan is not very meaningful)
        int scan = 0;

        int[] userNumber = new int[10];
        String[] player = new String[10];
        Double[] highScore = new Double[10];

        userNumber[0]= 10;
        userNumber[1]= 777;
        userNumber[2]= 5;
        userNumber[3]= 1234;
        userNumber[4]= 357;

        // set the rest to an invalid user #; otherwise these will have a value 0 by default
        userNumber[5]= INVALID_USER_NUM;
        userNumber[6]= INVALID_USER_NUM;
        userNumber[7]= INVALID_USER_NUM;
        userNumber[8]= INVALID_USER_NUM;
        userNumber[9]= INVALID_USER_NUM;

        player[0]= "Morpheus";
        player[1]= "Neo";
        player[2]= "Cereal Killer";
        player[3]= "Crash Override";
        player[4]= "Acid Burn";

        highScore[0]= 853797.67;
        highScore[1]= 999999.99;
        highScore[2]= 15097.34;
        highScore[3]= 864513.16;
        highScore[4]= 543188.68;

        // this represents the array index of the user across the arrays
        int indexOfUser = 0;

        // flag to indicate if we found a valid user
        boolean userFound = false;
        do
        {
            String replyBox = JOptionPane.showInputDialog("Enter User#");

            // consider trimming this replyBox value
            // If they enter "10  " (w/o quotes would you still want that to be valid)
            replyBox = replyBox.trim();

            scan = INVALID_USER_NUM; // default to an invalid user #
            try
            {
                scan = Integer.parseInt(replyBox);
            }
            catch (java.lang.NumberFormatException nfe)
            {
                // they didn't enter a valid integer, but you don't want to exit the program
            }

            // don't bother searching if it's invalid
            if (scan != INVALID_USER_NUM)
            {
                // loop through each user to see if you find the entered #
                for (int i = 0; i < userNumber.length && !userFound; i++)
                {
                    // we found this user
                    if (scan == userNumber[i])
                    {
                        indexOfUser = i;
                        userFound = true;
                    }
                }
            }

            if (!userFound)
            {
                // you should use replyBox instead of scan here
                //String messagefalse = String.format("Error %s is an Unknown User", scan);
                String messagefalse = String.format("Error: '%s' is an Unknown User", replyBox);
                JOptionPane.showMessageDialog(null, messagefalse);
            }

        } while (!userFound); // loop until we find a user

        // we've found a user - use the indexOfUser to index the arrays
        String messagetrue = String.format("%s, user# %s, has a high score of: %s", player[indexOfUser], userNumber[indexOfUser], highScore[indexOfUser]);
        JOptionPane.showMessageDialog(null, messagetrue);
    }
}