Home > OS >  how to display values in Array AND take user input in Array using java?
how to display values in Array AND take user input in Array using java?

Time:09-22

if I want my program to display information (values) but also take user input into the Array using Java, how is it done? Please guide me. When my program starts up, I want to see the values but I also want to allow the user to input value into the array

my code only allows user input but I also want to show values. how do I display values that I've hard coded?

CodePudding user response:

If you want to get an input for an array you need to get the size of array before creating the array. Then you can get input from the system. I have Provided you a sample program which will be useful for you to get inputs for an array. You can refer the java docs for various methods you could use.

 import java.util.Scanner;
    public class Test
    {
        public static void main(String[] args)
        {
            int n;
            Scanner sc=new Scanner(System.in);
            System.out.print("Enter Array Size:");
            n=sc.nextInt();
            int[] array = new int[n];
            System.out.println("Enter Array elements: ");
            for(int i=0; i<n; i  )
            {
                array[i]=sc.nextInt();
            }
    
            for (int i=0; i<n; i  )
            {
                System.out.println(array[i]);
            }
        }
    }  

You need to create the array of your required type and size then you have to get the inputs using a for loop for array elements.

  • Related