Java 如何使用Int引用字符串数组下标

Java 如何使用Int引用字符串数组下标,java,arrays,Java,Arrays,我的目标是从用户那里获得五个名称的列表,并将它们存储在一个数组中。然后,我需要向用户显示一个名字列表,每个名字前面都有整数,并允许用户选择哪个朋友是他/她最好的朋友。 我已经完成了部分,我需要用户的输入来表示他们最好的朋友。用户的输入必须是整数,而我的名称数组是字符串数组。我很难让用户提供的Int引用名称字符串数组中的特定下标 import java.util.Scanner; public class Question5 { public static void main(Strin

我的目标是从用户那里获得五个名称的列表,并将它们存储在一个数组中。然后,我需要向用户显示一个名字列表,每个名字前面都有整数,并允许用户选择哪个朋友是他/她最好的朋友。 我已经完成了部分,我需要用户的输入来表示他们最好的朋友。用户的输入必须是整数,而我的名称数组是字符串数组。我很难让用户提供的Int引用名称字符串数组中的特定下标

import java.util.Scanner;

public class Question5
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter five names");

        String[] names = new String[6];
        for (int subscript = 1; subscript <= 5; subscript++)
        {
            System.out.println("Enter friend " + subscript);
            names[subscript] = keyboard.next();
        }
        System.out.println("Here are all of those names");
        for (int subscript = 1; subscript <= 5; subscript++)
        {
            System.out.println("Friend " + subscript + " is " + names[subscript]);
        }
        System.out.println("Which friend is your best friend? (Enter an integer)");
        names[1] = "1"; names[2] = "2"; names[3] = "3"; names[4] = "4"; names[5] = "5"; //I am not sure if this line is helpful or needs to be deleted.

    }
}
使用keyboard.nextInt从用户处获取选择,然后从数组中检索名称:

System.out.println("Which friend is your best friend? (Enter an integer)");
System.out.println("You chose: " + names[keyboard.nextInt()]);

您可以将用户输入解析为整数,如下所示,并显示所选的最佳朋友:

int bestFriend = Integer.parseInt( keyboard.next() );
//names[1] = "1"; names[2] = "2"; names[3] = "3"; names[4] = "4"; names[5] = "5"; //I am not sure if this line is helpful or needs to be deleted.
System.out.println("You have selected " + names[bestFriend]);

请详细说明给出的答案:

在Java中,数组从索引0开始,创建长度为6的数组只是为了在索引1处开始迭代,这是在浪费第一个元素 或操作令牌默认情况下,令牌由空格字符分隔。虽然这可能与这个问题无关,但想象一下,在一个包含15个元素的列表中,用户必须在控制台上选择一个索引。如果用户输入11,则一切正常,但如果他意外添加了空格1,则选择1,尽管输入无效,但没有数字包含空格。这就是为什么我更喜欢使用和解析结果,而不是使用前面的方法。 最后,这是上述要点的一个示例实现:

import java.util.Objects;
import java.util.Scanner;

public class FriendSelector {
    private static class InvalidSelectionException extends RuntimeException {
        private static final long serialVersionUID = -8022487103346887887L;
    }

    public static void main(String[] args) {
        FriendSelector friendSelector = new FriendSelector();

        String[] friends = friendSelector.promptUserForFriendList(5);
        System.out.println(); // Add a newline for separation.

        // Present the list of friends to the user.
        System.out.println("These are your entered friends:");
        printList(friends);
        System.out.println(); // Add a newline for separation.

        // Let the user select his/her best friend.
        int bestFriendIndex;
        do {
            bestFriendIndex = friendSelector.promptUserForBestFriend(friends);
        } while (bestFriendIndex == -1);

        System.out.printf("You selected %s as your best friend.\n", friends[bestFriendIndex]);
    }

    /**
     * Print a list to the console. Format: "[index + 1] element".
     *
     * @param list the list, not null
     */
    private static void printList(String[] list) {
        Objects.requireNonNull(list);

        for (int i = 0; i < list.length; i++) {
            System.out.printf("[%d] %s\n", (i + 1), list[i]);
        }
    }

    /*
     * Note that this scanner MUST NOT be closed, this would possibly interfere with
     * other program parts which operate on System.in.
     */
    private final Scanner scanner;

    public FriendSelector() {
        scanner = new Scanner(System.in);
    }

    /**
     * Prompt the user to populate a list of friends.
     *
     * @param length how many friends should be named
     * @return a list of friend names
     */
    public String[] promptUserForFriendList(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("length must be positive");
        }

        System.out.printf("Enter the names of %s friends, please.\n", length);

        String[] names = new String[length];
        for (int i = 0; i < names.length; i++) {
            System.out.printf("Name %d: ", i + 1);
            names[i] = scanner.nextLine();
        }

        return names;
    }

    /**
     * Prompt the user to select the best friend of the provided friends.
     *
     * @param friends an array of friend names, must be non-null
     * @return the index of the best friend, or -1 if none valid entry was selected.
     */
    public int promptUserForBestFriend(String[] friends) {
        Objects.requireNonNull(friends);

        try {
            System.out.printf("Which friend is your best friend [1,%d]: ", friends.length);

            // Get the selected array index.
            String selectionString = scanner.nextLine();
            int selection = Integer.parseInt(selectionString);
            int selectedIndex = selection - 1;

            if (selectedIndex < 0 || selectedIndex >= friends.length) {
                throw new InvalidSelectionException();
            }

            return selectedIndex;
        } catch (NumberFormatException | InvalidSelectionException e) {
            System.out.printf("Invalid input: You didn't enter an integer in the range [1,%d]\n", friends.length);
            return -1;
        }
    }
}

最后一行没有帮助。它清除了用户输入的五个名称。我怀疑您想要int choice=keyboard.nextInt;。然后可以使用choice作为数组下标。