Search code examples
javawhile-loopdo-whileisbn

Creating do-while loop to prompt user if they want to enter another ISBN


So as a project for my class I am required to make a program that has the user enter the first n digits of an ISBN number and responds with the tenth digit. I have searched endlessly for something that will allow my program to ask the user if they want to run the program again and then have it run the program again if they enter 'yes' or 'Y'. What I have found hasn't worked, usually it just ends up looping "Would you like to enter another ISBN' without actually having them enter an ISBN. My code is below, thank you guys for any help!

import java.util.Scanner;
public class ISBNCheckSum {

    public static void main(String[] args) 
    {
        Scanner keyboard = new Scanner(System. in );
        // limiter 
        int isbn10 = 9;
        // to take in response of user
        long userResponse;
        // accumulator 
        int ISBnNum = 1;
        //current count of ISBN
        long isbnCount = 0;
        // This is used to multiply the userresponse by 1,2,3... up to 9
        int multiplier = 1;

        while (ISBnNum <= isbn10) 
        {
            System.out.println("Please ISBN number  " + ISBnNum);
            //to enter the User response
            userResponse = keyboard.nextInt();
            //Multiply the user response by multiplier variable
            userResponse = userResponse * multiplier;
            //add to accumulator 
            ISBnNum = ISBnNum + 1;
            // put user into final answer
            isbnCount = isbnCount + userResponse;
            // increase multiplier
            multiplier = multiplier + 1;
        }

        long checkSum;
        checkSum = isbnCount % 11;
        System.out.println(checkSum);
    }
}
}

Solution

  • Try something like this (I have changed the iSBnNum variable name):

        boolean askAgain = true;
        while (askAgain) {
            iSBnNum = 1;
            while (iSBnNum <= isbn10) {
                System.out.println("Please ISBN number  " + iSBnNum);
                // to enter the User response
                userResponse = keyboard.nextInt();
                // Multiply the user response by multiplier variable
                userResponse = userResponse * multiplier;
                // add to accumulator
                iSBnNum = iSBnNum + 1;
                // put user into final answer
                isbnCount = isbnCount + userResponse;
                // increase multiplier
                multiplier = multiplier + 1;
            }
    
            System.out.println("Ask again (Y/N)?");
            String answer = keyboard.next();
    
            askAgain = answer.equalsIgnoreCase("Y");
        }