I need to create random numbers that will run through an array without duplicates.
The problem is the duplication and I can't use any of the utils except the Scanner for input like java.util.Random or java.util.ArrayList.
I use a function called random and the function newNum is where I need what I have asked.
The problam is it's printing duplicate numbers and giving me an error after the eighth or ninth print.
package exercise;
import java.util.Scanner;
public class Bingo {
static int size = 10;
static int num;
static int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private static Scanner sc;
public static void main(String[] args) {
System.out.print("Press Enter to start: ");
sc = new Scanner(System.in);
System.out.println("");
int num = random();
while (size > 0) {
String input = sc.nextLine();
if (input.isEmpty()) {
System.out.println(num);
size--;
newArray(num);
num = random();
newNum(num);
} else {
System.out.println("Input was enterd!");
break;
}
}
System.out.println("End of program");
}
public static int random() {
int max = 10;
double r = Math.random();
int num = (int) (r * max + 1);
return num;
}
public static int newNum(int num) {
int i = 0;
while (num != arr[1]) {
if (i <= num) {
i++;
} else {
num = random();
}
}
return num;
}
public static int newArray(int num) {
int[] tempArray = arr;
arr = new int[size];
int x = num - 1;
for (int i = 0; i < x; i++) {
if (i < size) {
arr[i] = tempArray[i];
}
}
for (int i = num; i < size; i++) {
if (i < size) {
int y = i - 1;
arr[y] = tempArray[i];
} else {
int a = size - 1;
arr[a] = tempArray[size];
}
}
return num;
}
}
Aucun commentaire:
Enregistrer un commentaire