java 获取用户输入并将其添加到数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14013074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:44:34  来源:igfitidea点击:

Taking user input and adding it to an array

javaarrayswhile-loopuser-input

提问by hijaked79

So I'm relearning java and it's been a while since. I'm trying to build a basic program (explained in code comments) and I'm having trouble remembering how to take user input and add it into an array. I'm having more trouble remembering how to loop through the user inputs and testing if they input anything as well as appending the input to the array if they do input something.

所以我正在重新学习 Java 并且已经有一段时间了。我正在尝试构建一个基本程序(在代码注释中进行了解释),但我无法记住如何获取用户输入并将其添加到数组中。我在记住如何遍历用户输入并测试他们是否输入任何内容以及如果他们输入某些内容时将输入附加到数组时遇到了更多麻烦。

//This program will ask user for for there favorite four games
//If the answer is blank, it will ask again for a game title
//The program will than store there answers into an array
//The program will than display the array in random order
//it will then give the amount of games in the array with an integer



import java.util.*;

public class MultipleClassesMain {


public static void main(String[] args) {

    //Array holds 4 string inputs from user
    String gameArray[] = new String[4];

    //importing scanner element-------
    Scanner input = new Scanner(System.in);

    //Introduction---------------
    System.out.println("Hey there!!!");
    System.out.println("Please tell us four game titles you like to play!!!");

    //Asks what game user likes and takes user input into a variable
    System.out.println("So what a game you like?: ");
    String temp = input.nextLine();

    //This loop will test against blank user input
    while (temp.equals("") || (temp.equals("   ")){
        System.out.println("Your game can't be blank.  Enter again: ");

        }

    }

}

}

This is the code I have so far. If anyone could give me some constructive criticisms and some pointers on how to loop through user input(testing for input) and appending the inputs to the array, I'd greatly appreciate it.

这是我到目前为止的代码。如果有人能给我一些关于如何循环用户输入(测试输入)并将输入附加到数组的建设性批评和一些指示,我将不胜感激。

Cheers

干杯

回答by fge

First: use a Listinstead of an array for user input. Just .add()your inputs to it. But see below for a better solution, ie using a Set.

第一:使用 aList而不是数组来进行用户输入。只是.add()你的投入。但请参阅下文以获得更好的解决方案,即使用Set.

Second: Stringhas a .trim()method which removes whitespaces both at the beginning and end, use that and test for the empty string using .isEmpty().

第二:String有一个.trim()方法可以删除开头和结尾的空格,使用它并使用.isEmpty().

Third: a Listdoes not detect duplicate entries, however a Setdoes, provided that its entries correctly implement equals()and hashCode(), which Stringdoes, so the following code accounts for this (the .add()method of a Setreturns true if and only if the set is modified as a result of the operation).

第三: aList不检测重复条目,但是 aSet可以,前提是它的条目正确实现了equals()and hashCode()String所以下面的代码说明了这一点(当且仅当集合因以下原因被修改时,a的.add()方法Set返回 true操作)。

Sample code:

示例代码:

public static void main(final String... args)
{
    // Set of valid user inputs
    final Set<String> gameList = new HashSet<String>();
    // Object from which user inputs are read
    final Scanner in = new Scanner(System.in);

    // Introduction
    System.out.println("Hey there!!");
    System.out.println("Please tell us four game titles you like to play!!!");

    // What the user enters
    String input;

    // Check that 4 titles have been entered, don't get out of the loop until then
    while (gameList.size() < 4) {
        System.out.print("Enter the name of a game: ");
        // Read one input, trim all beginning and trailing whitespaces
        input = in.nextLine().trim();
        // If the resulting string is empty, input is invalid: ask for another
        if (input.isEmpty()) {
            System.out.println("Empty inputs not accepted!");
            continue;
        }
        if (!gameList.add(input))
            System.out.println("You have already selected this game (" + input + ')');
    }

    // Print out the list of inputs
    System.out.println("The list of selected games is: " + gameList);

}

回答by Achintya Jha

for (int i = 0; i < 4; i++) {
        String temp = input.nextLine();
        if (temp.equals("") || (temp.equals("   "))) {
            System.out.println("Your game can't be blank.  Enter again: ");
            i--;
        } else
            gameArray[i] = temp;

    }

Try this . This is what you asking for..yes?

试试这个 。这就是你要的……是吗?