列出用户输入

时间:2014-11-11 21:22:49

标签: java java.util.scanner user-input

"编写一个Java程序,要求用户输入五个数字。

该程序应防止用户多次输入相同的号码。它还应该在屏幕上打印用户已输入的数字。"

输出应该变为:

请输入一个数字:3

列表:3

请输入一个数字:16

列表:3 16

请输入一个数字:16

号码已经在列表中!!!再试一次 !!!

列表:3 16

请输入一个数字:23

列表:3 16 23

当然,这些数字并不一定是我所说的。请帮忙?到目前为止我所拥有的:

    Scanner in = new Scanner(System.in);

    System.out.print("Please, enter a number: ");
    int num[] = new int[5];

    for (int i = 0; i < num.length; i++)
    {
        num[i] = in.nextInt();
    }

编程很难..我尝试单独的用户输入并以这种方式列出,但我不知道如何检查是否已输入数字。

非常感谢帮助!

3 个答案:

答案 0 :(得分:1)

我保证这不是你老师想要你做的事情。 BUT

public static boolean arrayContains(String[] arr, String targetValue) {
    return Arrays.asList(arr).contains(targetValue);
}

是最快捷的方式。

如果你不能这样做,或者不习惯这样做,那么循环通过阵列将是另一种解决方案。也许是你老师想要你使用的那个。

public static boolean isInArray(String[] arr, String targetValue) {
    for(String s: arr){
       if(s.equals(targetValue))
          return true;
     }
     return false;
 }

答案 1 :(得分:1)

这是一个接近你的知识的基本答案,我希望你能理解。

for (int i = 0; i < num.length; i++){   
    int current = in.nextInt();         // getting first input for number 'i'

    while( Arrays.asList(num).contains(current)){    // checking if number already exists
       // Number already exist, will loop this untill you give a unique one
       System.out.print("Number already exist. Try again: ");
       current = in.nextInt();
    }

    // Printing the output
    System.out.print("List: ")
    for(var j =0; j < i; j++){
        System.out.print(num[i]+" ");

}

我将Array转换为List以检查号码是否已存在。如果您感觉不舒服,可以使用更基本的功能进行切换,例如DejaVuSansMono提供的isInArray()

答案 2 :(得分:0)

你想在这里使用while循环而不是for循环。当你不知道循环执行的次数时,会使用while循环。 for循环通常用于固定数量的执行。

Scanner in = new Scanner(System.in);
int num[] = new int[5];
int index = 0;


while(index != 5)
{
    boolean add = true;
    System.out.println("Please, enter a number: ");
    int tempInt = in.nextInt();
    for(int i = 0; i < num.length; i++)
    {
        //check if num[i] == tempInt if it does set add to false because its already in the array
    }
    //if add is true add number to num[index] and increment index
    //if add is false send message to user saying that the number is already in the list
    for(int i = 0; i < index; i++)
    {
        System.out.print(num[i] + " ");
    }
}

这应该给你一个开始。我没有为你写一切,但我给了你一个模板和一些评论。希望这可以帮助你弄清楚其余部分。

相关问题