Okay so I have this server that creates a randomly generated array, then tells the user to remove a number. However I added a section so that if the user selects a number that's NOT in the array then it tells them to select again... It successfully tells the user that's not in the array and to pick again and then it just allows me to enter numbers freely without continuing the program... here is my code and here is what I get as responses
import java.util.Random;
import java.util.Scanner;
public class Server {
public static boolean checked = false;
public static int removed;
public static int inserted;
public static int index;
public static int[] array = new int[50];
public static void generateArray(){
Random random = new Random();
for(int i=0; i<array.length; i++){
int x = random.nextInt(101);
if(x>0){
array[i]= x;}
else{
i--;}
for (int j=0; j < i; j++) {
if (array[i] == array[j]) {
i--;
}
}
}
for(int i=0; i<array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void insertRemove(){
Scanner input = new Scanner(System.in);
if(checked == false){
System.out.println("Select a number to be removed.");
checked = true;
}
removed = input.nextInt();
Server.checkValid();
if(checked == true){
System.out.println("Select a new number to be inserted.");
inserted = input.nextInt();
System.out.println("Select an index for the number to be inserted at.");
index = input.nextInt();
}
}
public static void checkValid(){
boolean repeat = false;
loop:
for(int i=0; i<array.length; i++){
for(int j=0; j<array.length; j++){
if(array[i] == removed){
checked = true;
Server.insertRemove();
}
else{
System.out.println("That number isn't in the array.");
checked = false;
repeat = true;
if(checked == false){
break loop;
}
else{}
}
}
}
if(repeat == true){
Server.insertRemove();
}
}
}
Responses
It is also only checking the first number of the array, due to the else... break;
but if i do a double loop using for(int j=0; j<array.length j++)
then it prints That number isn't in the array.
50 times.
43 27 62 44 85 15 61 17 59 20 84 73 60 49 26 54 41 5 64 96 32 68 86 7 52 53 47 19 58 18 70 74 50 28 38 91 89 1 36 42 78 45 97 57 9 29 55 2 40 90
Select a number to be removed.
0
That number isn't in the array.
Select a number to be removed.
43
43
43 // <----as you can see it's still allowing me to just type in 43
43
There is a main method that calls this...
public class Main {
public static void main(String[] args){
Server.generateArray();
Server.insertRemove();
}
}
Basically how can I fix this loop that is currently allowing me to insert numbers, so that if I insert something not in the array then something actually in the array then it will allow me to continue the normal program and ask me for a number to insert, index to be inserted at, etc.