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



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

}

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

干杯

首先:使用List而不是数组进行用户输入。只需.add()您的输入即可。但是请参阅下文以获取更好的解决方案,即使用Set.

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

第三:List不会检测到重复的条目,但是Set会检测到重复的条目,前提是其条目正确实现了equals()hashCode()String这样做,因此以下代码对此进行了解释(Set.add()方法返回true当且仅当由于操作而修改了集合)。

示例代码:

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

试试这个.这就是你所要求的..是的?

相关内容

  • 没有找到相关文章