Ecem Şimşek Ecem Şimşek - 1 month ago 11
Java Question

Getting do-while error

So, I prompt from user to enter variable. If variable smaller than 0 and bigger than 10. If user enter either <0 and >10, I want to ask from user to enter the number again. I enter 4 when asking time, it saying you entered wrong. But at second attempt it works well. For example: If I enter 25, it print message which is " you entered wrong." Why am I getting this message even my input is proper for condition at first attempt?

import java.util.*;
import java.io.*;


public class abc{
public static void main(String args[]) throws Exception{


int velocity;
int time;

System.out.print("Enter the velocity");

Scanner sn = new Scanner(System.in);

velocity = sn.nextInt();


System.out.println("Enter the time");

time=sn.nextInt();


do{

System.out.println("you entered wrong format/d Please Try Again");

time=sn.nextInt();

}while(time<0 || time>10);

}
}

Answer

Please consider the following implementations (see the comments).

do-while loop

// Assuming the time value is not valid.
boolean isValidTime = false;

do {
    System.out.println("Enter the time: ");
    time = sn.nextInt();

    if (time < 0 || time > 10) {
        System.out.println("You have entered invalid time value!");
    } else {
        // The time value is valid now!
        isValidTime = true;
    }
// While the time value is not valid…
} while (!isValidTime);

while-do loop

// Assuming the time value is not valid.
boolean isValidTime = false;

// While the time value is not valid…
while (!isValidTime) {
    System.out.println("Enter the time: ");
    time = sn.nextInt();

    if (time < 0 || time > 10) {
        System.out.println("You have entered invalid time value!");
    } else {
        // The time value is valid now!
        isValidTime = true;
    }
}
Comments