In: Computer Science
in Java, I need to create an array of animals. The user is going to be prompted to enter the size of the array where a valid size is 10-30(inclusive). Then I have to populate only half of this array. I am not sure how to do that so can you please write comments explaining.
Thank you
An array of animals is created keeping in mind it will consists of the name of the animals . so it is declared as a string.
As question states the code is below. It is self explanatory with comments and output.
CODE:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is
public. */
class Check
{
public static void main (String[] args) throws
java.lang.Exception
{
// your code goes here
int i;
//This reads the input provided by
user using keyboard
Scanner scan = new
Scanner(System.in);
//prints the statement which asks
user to enter size of array
System.out.print("Enter the size of array animals (10-30): ");
// This method reads the number provided using keyboard
int n = scan.nextInt();
//create an array of string data type with size as defined by the
user
String[] animals = new String[n];
//traversing the array from 0 index to half to what user has
entered
for(i=0;i<n/2;i++){
//populating half the array with string "abc"
animals[i]="abc";
}
for(i=0;i<n;i++){
//display all the elemnts of the array
System.out.println("entered:"+animals[i]);
}
}
}
INPUT:
10
OUTPUT:
entered:abc entered:abc entered:abc entered:abc entered:abc entered:null entered:null entered:null entered:null entered:null