Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hi my program is looping if i type ten the firsr time it says correct and ends the program but when i type second time it wont end it will keep going

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
   }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading