简体   繁体   中英

Java - set value range

I am working on a Java 1.8 script in which I am trying to set a user input number range, in which user can only enter number between 0 and 1000. I am trying to set the range using the below code, but it is still allowing me (the user) to enter number greater than 1000.

} while (0 < digit && digit < 1000);

I tried searching for similar questions here, but a lot of answers I find basically recommend doing what I am doing below, and that seems to work for other users, so I don't understand why it is not working for me.

The code above is not throwing any errors, so I am baffled as to why it is still allowing me to enter number bigger than 1000. I am a Java novice so possibly some logic error...

This is my full code below. The purpose of the script is to enter number between 0 and 1000 and have the system calculate the sum of its digits. It is successfully calculating the sum, but when I enter a number greater than 1000, the sum is zero...

        System.out.println("Enter a number between 0 and 1000.");
        int num = 4567;
        int sum = 0;
        while (num > 0 && num <1000) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println("The sum of the digits is " + sum); 

To take user input, requiring it to be in the range of 1..999, you'll need something like this:

do {
    num = // get the input
} while (num < 1 || num > 999);

Your second loop is completely skipped if the number is 1000 or greater -- the sum will be the initial 0 for any such values. Maybe the second condition is not necessary at all -- it should work just fine for numbers of any size:

while (num > 0) {
    sum += num % 10;
    num /= 10;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM