1
import java.util.Scanner;
import java.util.*; 

public class ICT2100_LabTutorial2 {
    public static void main(String args[]){

        Scanner input = new Scanner(System.in);

        System.out.println("Enter your title: ");

        String title = input.nextLine();

        int page;
        int counter = 1;

        String value;

        do{
            System.out.println("Chapter " + counter++);
            value = input.nextLine();
            if(value.length() > 44)
            {
                System.out.println("More than 44 characters");
            }

            System.out.println("Enter a page number: ");
            page = input.nextInt();

            while((page < 1) && (page > 1500)){
                System.out.println("Enter a page number that is between 1 to 1500: ");
                page = input.nextInt();
            }

        }while(!value.equals("END"));

        System.out.println("you ended the process");
    }
}

I am trying to add page number into my code whereas the code will tell the user to enter the page number once again if it is not a number that's either 1 to 1500.

I am able to run the code properly and can end the program without the page counter, but the program breaks or doesn't run as intended once I added in the page counter segment.

Edit: So apparently you will have to add input.nextLine(); after input.nextInt(); for the program to actually go ahead and fetch the next instruction instead of being stuck in a loop. Correct me if I am wrong, still learning and thanks for all the help.

3 Answers 3

2

Use

while((page < 1) || (page > 1500)) {
...
}
Sign up to request clarification or add additional context in comments.

2 Comments

This will print out the error message if the user has supplied a number between 1 and 1500. The author is looking to have the error message printed when the user enters a number outside of the 1 - 1500 boundary.
@JohnStark Thanks, I have corrected the while condition accordingly.
1

Try to use Or condition instead of and

while(page < 1 || page > 1500)

Both conditions cant be true at the same time that's why remove && with || as shown above.

Comments

1

You are using an AND operator which returns true when both conditions are true. But in your case it should return true when either of conditions inside while loop is true which is what OR operator does.

So use OR operator (||) isnide the while loop

while((page < 1) || (page > 1500)){
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.