Home > Software engineering >  Hi my program is looping if i type ten the firsr time it says correct and ends the program but when
Hi my program is looping if i type ten the firsr time it says correct and ends the program but when

Time:01-19

int[] array = new int[10];
    System.out.println("Give me an integer");
int userinteger = input.nextInt();
if (userinteger >= 0 && userinteger < array.length) {
System.out.println("Correct");
} else 
while (userinteger >= 0 || userinteger < array.length) {
System.out.println(" Wrong please try again");
array[0] = input.nextInt();

//my program will run if I type ten the first time it stops which is what I want but if I type twelve which is wrong and then ten it won't say correct please help me I don't know why this is happening

CodePudding user response:

The reason why it will not print out "correct" is because you are running an if else statement and your while loop is placed within the else. Therefore if you input 12 and then input 10, the code that prints out "correct" is outside of the scope. Another issue you have is that you are assigning the input to array[0] and then not comparing that value anywhere, instead use your original variable userinteger. To fix this you can

int[] array = new int[10];
System.out.println("Give me an integer");
int userinteger = input.nextInt();
while (userinteger >= 0 || userinteger < array.length) {
   if (userinteger >= 0 && userinteger < array.length) {
       System.out.println("Correct");
       break; // Since it is correct you want to break out of the loop
   }
   else {

       System.out.println(" Wrong please try again");
       userinteger = input.nextInt();
   }
  •  Tags:  
  • Related