import java.util.Random; ? public class ArrayNum1 { static Random r = new Random
ID: 3575745 • Letter: I
Question
import java.util.Random;
?
public class ArrayNum1 {
static Random r = new Random(10);
static int [] array = new int [20];
public static void main(String[] args) {
// creates an array of 20 elements
//assigns random numbers to the 20 elements from 1-20
for (int i = 0; i< array.length; i++) {
array[i] = r.nextInt(20)+1;
}
//prints the array
printArray();
//calls duplicate_method
duplicate_method();
System.out.println(" No DUPS");
printArray();
}
public static void duplicate_method( ) {
int number;
int count = 0;
boolean flag = true;
while(flag) {
flag = false;
// remove duplicates
for (int i = 0; i < array.length; i++) {
for (int j = i+1; j < array.length; j++) {
// loops through each number in the array to see if there are duplicates
if (array[i] == array[j]){
//if there are any duplicates, the duplicate's value will be changed to 0
array[j] = 0;
flag = true;
}
}
}
System.out.println(" Dups removed:");printArray();
// replace duplicates with zero
for (int i = 0; i< array.length; i++) {
if (array[i]==0) { array[i] = r.nextInt(20)+1; }
}
System.out.println(" Repopulated:");printArray();
}
}
public static void printArray() {
for (int i = 0; i < array.length -1; i++) {
System.out.print(array[i] + " ");
}
}
}
Program 1 ArrayNum1 What would the code do if line 27 was set to true, that is: flag true;? Why is this happening?Explanation / Answer
Please find my comment at line 27.
import java.util.Random;
public class ArrayNum1 {
static Random r = new Random(10);
static int [] array = new int [20];
public static void main(String[] args) {
//creates an array of 20 elements
//assigns random numbers to the 20 elements from 1-20
for (int i = 0; i< array.length; i++) {
array[i] = r.nextInt(20)+1;
}
//prints the array
printArray();
//calls duplicate_method
duplicate_method();
System.out.println(" No DUPS");
printArray();
}
public static void duplicate_method( ) {
int number;
int count = 0;
boolean flag = true;
while(flag) {
// if flag is set to be true, then while loop never ends, it will be infinite loop
flag = false;
//remove duplicates
for (int i = 0; i < array.length; i++) {
for (int j = i+1; j < array.length; j++) {
//loops through each number in the array to see if there are duplicates
if (array[i] == array[j]){
//if there are any duplicates, the duplicate's value will be changed to 0
array[j] = 0;
flag = true;
}
}
}
System.out.println(" Dups removed:");printArray();
//replace duplicates with zero
for (int i = 0; i< array.length; i++) {
if (array[i]==0) { array[i] = r.nextInt(20)+1; }
}
System.out.println(" Repopulated:");printArray();
}
}
public static void printArray() {
for (int i = 0; i < array.length -1; i++) {
System.out.print(array[i] + " ");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.