为什么这个 for 循环不允许我在第一个循环中输入文本?

发布于 2024-08-13 06:04:21 字数 627 浏览 2 评论 0原文

我想要做的是要求用户输入一些字符串来读入数组,然后要求用户输入该数量的字符串并将它们读入数组。当我运行这段代码时,它从不要求我在第一个 for 循环的第一个循环中输入内容,只是打印出“String #0: String #1:”,然后我就可以输入文本了。这是为什么?我做错了什么?

import java.util.Scanner;

public class ovn9 
{
public static void main(String[] args)
{
    Scanner sc=new Scanner(System.in);

    System.out.print("Number of inputs: ");

    int lines= sc.nextInt();
    String[] text=new String[lines];

    for(int x=0; x<text.length; x++)
    {
        System.out.print("String #"+x+": ");
        text[x] = sc.nextLine();
    }

    for(int y=0; y<text.length; y++)
        System.out.println(text[y]);

}
}

What I want to do is ask the user for a number of strings to read into an array, and then ask the user to input that number of strings and read them into the array. When I run this code it never asks me for an input the first cycle of the first for-loop, just prints out "String #0: String #1: " and then I can input text. Why is that and what did I do wrong?

import java.util.Scanner;

public class ovn9 
{
public static void main(String[] args)
{
    Scanner sc=new Scanner(System.in);

    System.out.print("Number of inputs: ");

    int lines= sc.nextInt();
    String[] text=new String[lines];

    for(int x=0; x<text.length; x++)
    {
        System.out.print("String #"+x+": ");
        text[x] = sc.nextLine();
    }

    for(int y=0; y<text.length; y++)
        System.out.println(text[y]);

}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狂之美人 2024-08-20 06:04:21

缓冲。

nextInt() 不会消耗输入缓冲区中输入输入数量时放置的换行符。在 for 循环的第 0 次迭代中,缓冲区中已经有一行输入,nextLine() 可以立即完成,程序只会在第 1 次迭代中等待新的输入行。忽略换行符在输入中,您可以在进入 for 循环之前添加另一个 nextLine() 调用。

Buffering.

nextInt() does not consume the newline in the input buffer that was put there when you entered the number of inputs. In the iteration 0 of the for loop, there's already a line of input in the buffer and nextLine() can complete immediately and the program will wait for new input line only in iteration 1. To ignore the newline in the input, you can add just another nextLine() call before entering the for loop.

年华零落成诗 2024-08-20 06:04:21

也许您应该更改循环以使用“sc.next()”

for ( int x = 0; x < lines; x++ ) {
    System.out.print("String #" + x + ": ");
    text[x] = sc.next();
}

它可以通过 Java API

String next() 进行解释:从此扫描仪查找并返回下一个完整标记。

String nextLine():使扫描器前进到当前行并返回跳过的输入。

Maybe you should change your loop to use 'sc.next()'

for ( int x = 0; x < lines; x++ ) {
    System.out.print("String #" + x + ": ");
    text[x] = sc.next();
}

It can be explained by the Java API

String next(): Finds and returns the next complete token from this scanner.

String nextLine(): Advances this scanner past the current line and returns the input that was skipped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文