English 中文(简体)
Why doesn t this for-loop let me input text the first cycle?
原标题:

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

}
}
最佳回答

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.

问题回答

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.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签