-3

I have a simple piece of code, but there is one part that I cannot complete. How do I print all the elements of an array after I have inputted them from the keyboard in a for loop,

here is the code. Thanks.

  final int MAX = 5;
  String [] names = new String[MAX];

  for(int index = 0; index < MAX; index++){
     System.out.println("Enter a name: ");
     names[index]=keyboard.nextLine();
  }
  System.out.println(names);
Exarch1982
  • 23
  • 4

4 Answers4

2

Use a forloop, to loop over the array.

for(int index = 0; index < names.length; index++){
  System.out.println(names[index]);
}
Jens
  • 67,715
  • 15
  • 98
  • 113
0

you can directly print as (faster as single loop):

 String [] names = new String[MAX];
 for(int index = 0; index < MAX; index++)
{
 System.out.println("Enter a name: ");
 names[index]=keyboard.nextLine();
 System.out.println(names[index]);
}

or you can do like this :

String [] names = new String[MAX];
for(int index = 0; index < MAX; index++)
{
 System.out.println("Enter a name: ");
 names[index]=keyboard.nextLine();
 }
 for(int index = 0; index < MAX; index++)
{
 System.out.println(names[index]);
 }
Prashant
  • 2,556
  • 2
  • 20
  • 26
0

Arrays.toString(names)call toString() api of Arrays class to print array.

public static String toString(Object[] a)

Returns a string representation of the contents of the specified array.

  for(int index = 0; index < MAX; index++){
     System.out.println("Enter a name: ");
     names[index]=keyboard.nextLine();
  }

  System.out.println(Arrays.toString(names));
atish shimpi
  • 4,873
  • 2
  • 32
  • 50
0
import java.util.Scanner;

public class ABC {
public static void main(String []args) {
    final int MAX = 5;
      String [] names = new String[MAX];
      Scanner input = new Scanner(System.in);
      for(int index = 0; index < names.length; index++){
         System.out.println("Enter a name: ");
         names[index] = input.nextLine(); //Getting names from keyboard
      }
        System.out.println("The names are as follows : "); 
      for (int i = 0; i < names.length; i++) {
        System.out.println(names[i]);     //Printing the names
    }
   }
}
CodeWalker
  • 2,281
  • 4
  • 23
  • 50