获取用户输入并将其添加到阵列

时间:2012-12-23 17:33:34

标签: java arrays while-loop user-input

所以我重新学习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: ");

        }

    }

}

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

干杯

2 个答案:

答案 0 :(得分:4)

首先:使用List代替数组进行用户输入。只需.add()您对它的输入。但请参阅下面的更好解决方案,即使用Set

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

第三:List未检测到重复的条目,但只有Set才能检测到条目,前提是其条目正确实施equals()hashCode()String是的,所以下面的代码说明了这一点(.add()的{​​{1}}方法返回true,当且仅当因操作而修改了集合时。)

示例代码:

Set

答案 1 :(得分:2)

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;

    }

试试这个。这就是你要求的......是吗?