如何使用Int引用String数组下标

时间:2019-04-20 21:47:59

标签: java arrays

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

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.

    }
}

3 个答案:

答案 0 :(得分:1)

使用keyboard.nextInt()从用户那里获得选择,然后从数组中检索名称:

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

仅详细说明给出的答案:

  • 数组在Java中从索引0开始,创建一个长度为6的数组只是为了从索引1开始迭代时,您正在“浪费”第一个元素
  • Scanner.nextInt()Scanner.next()对令牌进行操作(默认情况下,令牌之间用空格字符分隔)。尽管这可能与该问题无关,但请想象一下一个由15个元素组成的列表,用户必须在其中选择控制台上的索引。如果用户输入“ 11”,一切正常,但是如果他不小心添加了空格(“ 1 1”),则选择1,尽管输入应该无效(没有数字包含空格)。这就是为什么我更喜欢使用Scanner.nextLine()并解析结果而不是使用以前的方法的原因。

最后,这是上述几点的示例实现:

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