Why does this loop not allow me to enter text in the first loop?

What I want to do is ask the user about the number of lines to read into the array, and then ask the user to enter this number of lines and read them in the array. When I run this code, it never asks me to enter the first loop of the first for loop, just prints "String # 0: String # 1:" and then I can enter the text. Why is this 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]); } } 
0
source share
2 answers

Buffering.

nextInt() does not consume a new line in the input buffer that was placed there when you entered the number of inputs. In iteration 0 of the for loop, an input line already exists in the buffer and nextLine() , and the program will only wait for input of a new line at iteration 1. To ignore a new line at the input, you can simply add another nextLine() call before entering the for loop.

+4
source

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(); } 

This can be explained using the Java API.

String next (): finds and returns the next full token from this scanner.

String nextLine (): advances this scanner beyond the current line and returns a missed input.

0
source

Source: https://habr.com/ru/post/924551/


All Articles