Create a program called Initializers.java to practice creating and initializing
ID: 3602012 • Letter: C
Question
Create a program called Initializers.java to practice creating and initializing or setting the values in an int array, and accessing elements in that array in main:
Declare and instantiate an int array named array1 having size 10 using the Java array initializer syntax with { } to fill array1 with the even integers 2 through 20. Hint: use just one statement:
int[] array1 = { … };
Using a for loop, print out the elements in array1 all across one line, separated by single spaces, then print a blank line.
Now ask the user how long to make the array using the Scanner or Keyboard nextInt() method, and assign a new int array of that length to reference variable array1, then fill it with even integers starting with 2, using a for loop; finally, print array1’s values, using a for loop as above.
Hints: you will have to compute each value that you put into the array in the loop, and you will need to use array1.length() or the size the user types in as the limit in the two for loop conditions.
Explanation / Answer
Note : Could you please check the output .If you required any changes Just intimate.I will modify it.Thank You.
___________________
Initializers.java
import java.util.Scanner;
public class Initializers {
public static void main(String[] args) {
int num;
//Declaring an initializing an array with even numbers in one line
int array1[]={2,4,6,8,10,12,14,16,18,20};
//Displaying the elements in the array
for(int i=0;i<array1.length;i++)
{
System.out.print(array1[i]+" ");
}
System.out.println();
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
long startTime = System.currentTimeMillis();
//Getting the inputs entered by the user
for(int i=0;i<array1.length;)
{
System.out.print("Enter element#"+(i+1)+":");
num=sc.nextInt();
if(num%2==0)
{
array1[i]=num;
i++;
}
else
{
System.out.println("** Invalid.Input Must be even Number **");
}
}
//Displaying the array elements
for(int i=0;i<array1.length;i++)
{
System.out.print(array1[i]+" ");
}
long endTime =System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(" Time of Taking Inputs from user :"+totalTime+" milliseconds");
}
}
_______________
Output:
2 4 6 8 10 12 14 16 18 20
Enter element#1:2
Enter element#2:4
Enter element#3:6
Enter element#4:8
Enter element#5:10
Enter element#6:11
** Invalid.Input Must be even Number **
Enter element#6:12
Enter element#7:14
Enter element#8:16
Enter element#9:18
Enter element#10:20
2 4 6 8 10 12 14 16 18 20
Time of Taking Inputs from user :12035 milliseconds
__________Thank YOu
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.