Write a Java program that does the following: 1. Creates an array of 100 integer
ID: 3832708 • Letter: W
Question
Write a Java program that does the following:
1. Creates an array of 100 integers and fills the array with random number between 0 and 999.
2. Passes the array to a method called PickDivisibleBy3Ones which picks the elements that are divisible by 3 (for example 0,3,6,9 etc.) and puts them into a new array and returns this new array.
Make sure you print the original array, then print the new array after it has been created and populated by the divisible by 3 numbers that exist in the first array.
Attach a .zip of the exported project to this question.
This is what I have so far:
package NumberArrayPackage;
import java.util.Random;
public class NumberArray {
public static void main(String[] args) {
//Declaring variables
int sum = 0,count;
double average;
//Creating the Random Class Object
Random r = new Random();
//Creating an Integer Array Of size 100
int myThousand[] = new int[100];
//Populating random numbers between 1-999 into an array
for(int i = 0; i < 999; i++)
{
//Generating the random number between 1-100
myThousand[i] = r.nextInt(999) +1;
PrintA(myThousand[i]);
}
}
Explanation / Answer
NumberArray.java
import java.util.Random;
public class NumberArray {
public static void main(String[] args) {
//Declaring variables
int sum = 0,count;
double average;
//Creating the Random Class Object
Random r = new Random();
//Creating an Integer Array Of size 100
int myThousand[] = new int[100];
//Populating random numbers between 1-999 into an array
for(int i = 0; i < myThousand.length; i++)
{
//Generating the random number between 1-100
myThousand[i] = r.nextInt(999) +1;
}
PrintA(myThousand);
System.out.println("-----------------------------");
int newArr[] = PickDivisibleBy3Ones (myThousand);
PrintA(newArr);
}
public static void PrintA(int a[]){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
public static int[] PickDivisibleBy3Ones(int a[]){
int n =0;
for(int i=0;i<a.length;i++){
if(a[i]%3 ==0){
n++;
}
}
int b[]= new int[n];
for(int i=0,j=0;i<a.length;i++){
if(a[i]%3 ==0){
b[j]=a[i];
j++;
}
}
return b;
}
}
Output:
785 560 373 731 598 323 627 931 305 216 477 527 882 270 966 705 108 985 386 42 278 290 124 198 650 833 567 338 374 995 591 197 105 338 372 336 748 713 856 973 746 151 348 64 883 480 113 64 206 411 423 169 176 967 951 759 485 671 358 645 311 886 116 680 756 885 836 577 646 80 523 708 900 700 234 458 220 144 716 202 783 114 298 756 135 510 708 620 440 45 651 121 534 283 919 724 15 44 28 901
-----------------------------
627 216 477 882 270 966 705 108 42 198 567 591 105 372 336 348 480 411 423 951 759 645 756 885 708 900 234 144 783 114 756 135 510 708 45 651 534 15
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.