View the step-by-step solution to:

Question

If my first input is 9 digits and the second input is "end"- the program shows "end is

invalid...."

I am trying to have this do the same when I enter 12 digits. For some reason I have to enter "end" three times before it says invalid. How can I fix this?




 public static void main(String[] args) {

     

    Scanner input = new Scanner(System.in);

 System.out.print("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");

    String s = input.next(); 

    

    String output10 = ""; 

    String output13 = ""; 

     

    while (!"QUIT".equalsIgnoreCase(s)) { 

      char checkDigit;

      char checkSum = '0';

      if (s.length() == 9) { 

        int sum = 0; 

        for (int i=0; i < s.length(); i++) {

          sum = sum + ((s.charAt(i) - '0') * (i + 1));

        }

        if (sum % 11 == 10) {

          checkDigit = 'X';

        }

        else {

          checkDigit = (char) ('0' + (sum % 11));

        }

        output10 = output10 + "n" + s + checkDigit;

        System.out.print("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");

        s = input.next();

      }

       

       

       

      if (s.length() == 12) {

        int sum = 0;

        for (int i=0; i < s.length(); i++) {

          if (i % 2 == 0) {

            sum = sum + (s.charAt(i) - '0');

          }

          else {

            sum = sum + (s.charAt(i) - '0') * 3;

          }

          checkSum = (char) (10 - sum % 10);

          if (checkSum == 10) {

            checkSum = 0;

          }

          output13 = output13 + "n" + s + checkSum;

          System.out.print("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");

          s = input.next(); }   

      }

       

       

       

      else if (!"QUIT".equalsIgnoreCase(s)) {

        System.out.println(s + " is an invalid input. ");

        System.out.print("Enter the first 9 or 12 digits of an ISBN number. Enter QUIT to exit: ");

        s = input.next();

      }

    }

     

    System.out.println("The 10 digit ISBNs are " + output10);

    System.out.println("The 13 digit ISBNs are " + output13);

  }

}

Top Answer

The code is given below... View the full answer

Sign up to view the full answer

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question