Home > Net >  How to use a For loop to read user inputed data?
How to use a For loop to read user inputed data?

Time:05-07

How do i change my code to when i entered a number/integer the program will read it instantly goes on and the inputted integer will not appear in the bottom. just like the pictureexpected output

And my code is

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        int length;
        Scanner input = new Scanner(System.in);
        
        String[] names = new String[10];
        
        for(int counter = 0; counter < 10; counter  ){
            System.out.println("Enter the 10 integers");
            names[counter] = input.next();
        }
        
        input.close();
        
        System.out.println("Stored Integers");
        for(int counter = 0; counter < 10; counter  ){
            System.out.println(names[counter]);
        }
        System.out.println("SUCCESS");
    }
}

CodePudding user response:

You have to print element inside same for loop after scanner take input from user and concat previous input.

Here down is modified code:

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        int length;
        String mergElement = "";
        Scanner input = new Scanner(System.in);
        
        String[] names = new String[10];
        
        for(int counter = 0; counter < 10; counter  ){
            names[counter] = input.next();
            mergElement = mergElement   names[counter]   " ";
            System.out.println("Array db ("   mergElement   ")");
        }
        
        input.close();
    }
}

Output

23
Array db (23 )
12
Array db (23 12 )
22
Array db (23 12 22 )
40
Array db (23 12 22 40 )
20
Array db (23 12 22 40 20 )

  • Related