如何在 Java 的 for 循环中获取不同数据类型的多个用户输入?

我试图提示用户输入一个字符串,该字符串将存储在一个字符串数组中,然后是一个输入的 int,它将被放入一个 int 数组中。


我遇到了打印第一行的问题,但没有提示用户输入字符串。然后立即打印第二个打印语句,用户只能输入一个 int。


到目前为止,我有:


    int i, n = 10;

    String[] sentence = new String[1000];

    int[] numbers = new int[1000];




    for(i = 0; i < n; i++)

        {

        System.out.println("Enter String" + (i + 1) + ":");

        sentence[i] = scan.nextLine();


        System.out.printf("Enter int " + (i + 1) + ":");

        numbers[i] = scan.nextInt();

        }

作为输出,我得到:


Enter String 1:

Enter int 1:

在这里你可以输入一个 int,并将它存储到 int 数组中。但是您不能为字符串数组输入字符串。


请帮忙。


繁花如伊
浏览 122回答 3
3回答

开心每一天1111

这个问题是由于nextInt()方法造成的。这里发生的是该nextInt()方法使用用户输入的整数,而不是用户输入末尾的换行符,这是在您按下enter键时创建的。enter因此,当您在输入整数后按下时,下一次调用会nextLine()消耗新的换行符,该换行符在循环的最后一次迭代中没有消耗nextInt()。这就是为什么它String在循环的下一次迭代中跳过输入并且不等待用户输入String解决方案nextLine()您可以通过在调用后nextInt()调用来消耗换行符for(i = 0; i < n; i++){&nbsp; &nbsp; System.out.println("Enter String" + (i + 1) + ":");&nbsp; &nbsp; sentence[i] = scan.nextLine();&nbsp; &nbsp; System.out.printf("Enter int " + (i + 1) + ":");&nbsp; &nbsp; numbers[i] = scan.nextInt();&nbsp; &nbsp; scan.nextLine();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// <------ this call will consume the new line character}

千巷猫影

像这样放置 scan.nextLine() :for(i = 0; i < n; i++){&nbsp; &nbsp; System.out.println("Enter String" + (i + 1) + ":");&nbsp; &nbsp; sentence[i] = scan.nextLine();&nbsp; &nbsp; System.out.printf("Enter int " + (i + 1) + ":");&nbsp; &nbsp; numbers[i] = scan.nextInt();&nbsp; &nbsp; scan.nextLine();}

aluckdog

使用 sc.next(); 而不是 sc.nextLine(); 如果无法在第一次迭代中输入字符串值。Scanner sc = new Scanner(System.in);for(i = 0; i < n; i++);&nbsp; &nbsp; System.out.println("Enter String" + (i + 1) + ":");&nbsp; &nbsp; sentence[i] = sc.next();&nbsp; &nbsp; System.out.printf("Enter int " + (i + 1) + ":");&nbsp; &nbsp; numbers[i] = sc.nextInt();&nbsp; &nbsp; sc.nextLine();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java