我试图输入用空格隔开的整数,然后尝试检索它们。就这么简单,但是我做不到。

因此,我想做的是,首先询问用户要输入多少个数字,他/她将输入数字,然后输入中间带有空格的数字数量。

用户输入以空格分隔的数字后,我只想将其打印回来。

拟议的产出

How many numbers do you want to enter?

5

Please enter 5 integers seperated by a space

1 2 3 4 5

You entered:-

1
2
3
4
5


这是我做的:-

int amountofnumbers;

Scanner myinput = new Scanner(System.in);
Scanner myinput2 = new Scanner(System.in);

System.out.println("How many numbers do you want to enter?");
int amountofnumbers = myinput.nextInt();


System.out.println("Please enter" + amountofnumbers + "integers seperated by a space");
actualnumbers = myinput2.nextInt();

System.out.println("You entered:- ");
for (int i = 1; i <= amountofnumbers ; i++)
{
    System.out.println(actualnumbers);
}


结果

目前,它显示

1
1
1
1
1

最佳答案

问题是您尝试使用以下命令捕获所有五个逗号分隔的整数:
actualnumbers = myinput2.nextInt();实际上将仅读取一个int,在您的情况下为1

您需要以循环或字符串形式读取整数,然后可以在空格上进行拆分,然后打印数字。您不需要两个扫描仪,也不需要TheLostMind提到的扫描仪。看来您想循环执行,然后使用以下命令:

public static void main(String[] args) {
        int amountofnumbers;
        int[] actualnumbers;

        Scanner myinput = new Scanner (System.in);
        System.out.println ("How many numbers do you want to enter?");
        amountofnumbers = myinput.nextInt();

        actualnumbers = new int[amountofnumbers];
        for(int index=0; index<amountofnumbers; index++)
        {
            System.out.println ("Please enter");
            actualnumbers[index] = myinput.nextInt();

        }
         myinput.close();
         System.out.println("You entered:");
        for(int enteredNumber : actualnumbers){
            System.out.println (enteredNumber) ;
        }
    }


输出为:

How many numbers do you want to enter?3Please enter1Please enter2Please enter3You entered:123

10-02 00:37
查看更多