Question

Lab 8 October 29, 2016 1 Overview In this lab, you will use the BasedNumber class, where the UML diagram is given below. Well be adding exceptions to this class when the values of base or digits are independently illegal or mutually incompatible. lagram is givein BasedNumber - base: nt - digils: III digits: int BasedNuber(base: in, digits: int) glBas: in +get Digit(n: int): int gelValuc): int als(other: BasedNuer): boolcanu You should modify this source so that the constructor for BasedNumber throws two unchecked exceptions (which you should define). It should throw an IllegalBaseException when the base is less than one. It should throw an IllegalDigitException when the digits array is either empty or contains a illegal value (either less than zero or equal or exceeding the base - remember that digits of a base n number must be in the range [0, n)). In addition to these exceptions, whats something else that could go wrong (not in the constructor)? What is an appropriate exception to throw at this point? 2 Driver You will also create a driver class. This class should prompt the user for a base and a space-separated list of digits and create a new instance of BasedNumber and display the result of the getValue method. The exceptions you added in the constructor should crash the program on illegal input. Make sure they do Let me see your progress at this point. Then, handle the errors so that your program never crashes on invalid input, but displays a (problem- specific) error message and re-prompts the user when something is wrong. You should also

Output

Enter base: 2

supply a list of digits separated by space: 1 0 0 1

The value for Base = 2 and digits = 1 0 0 1 is 9

Enter base: 16

supply a list of digits separated by space: 99

All digits must be in the range [0,n)

Enter base: 16

supply a list of digits separated by space: 9 9

The value for Base = 16 and digits = 9 9 is 153

Enter base: 2

supply a list of digits separated by space:

All digits must be in the range [0,n)

Enter base: 0

supply a list of digits separated by space: 1 0 0

Base Should be > 1

Enter base: 3

supply a list of digits separated by space: d 5

Digits must be integers

All digits must be in the range [0,n)

Template

package lab8;

import java.util.Arrays;

import java.util.Scanner;

public class Lab8 {

   public static void main(String[] args) {

       Scanner in = new Scanner(System.in);

       while(true) {

           // prompt user to supply a base

           // parse the base as an integer

           //

           // prompt user to supply a list of digits separated by space

           // parse the input string (for digits) to an array of digits

           //

           // create a based number object of the base and the digit array and print its value

           //

           // catch exceptions as required (number format, illegal base, illegal digits)

       }

       in.close();

   }

}

// define illegal base exception class

//

// define illegal digit exception class

class BasedNumber {

   private int base;

   private int[] digits;

   BasedNumber(int base, int[] digits) {

       // check base and throw exception if it is not great than 1

       // if the digit array is empty

       // if the digits is not within legal range (specified by the base)

   }

   int getBase() { return base; }

   int getDigit(int n) { return digits[n]; }

   int getValue() {

       int ret = 0;

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

           ret = ret * base + digits[i];

       }

       return ret;

   }

   boolean equals(BasedNumber that) {

       return getValue() == that.getValue();

   }

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the required program along with its output. Please see the comments against each line to understand the step.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;

class Lab8 {
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        while(true) {
            // prompt user to supply a base
            System.out.println("Enter base: ");
            //   parse the base as an integer
            int base = in.nextInt();

            // prompt user to supply a list of digits separated by space
            System.out.println("Enter a list of digits separated by space: ");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = br.readLine();
            String[] numStrings = line.split(" ");
            int nums[] = new int[numStrings.length];
            //   parse the input string (for digits) to an array of digits
            try {

                for(int i=0; i<numStrings.length; i++) {
                    nums[i] = Integer.parseInt(numStrings[i]);
                }
                // create a based number object of the base and the digit array and print its value
                BasedNumber number = new BasedNumber(base, nums);

                System.out.println(number);
                // catch exceptions as required (number format, illegal base, illegal digits)
            }catch (NumberFormatException e){
                System.out.println("Digits must be integers");
            }catch (IllegalBaseException e){
                System.out.println(e.getMessage());
            }catch (IllegalDigitException e){
                System.out.println(e.getMessage());
            }
        }
    }
}

// define illegal base exception class
class IllegalBaseException extends RuntimeException{
    public IllegalBaseException(String message) {
        super(message);
    }
}

// define illegal digit exception class
class IllegalDigitException extends RuntimeException {
    public IllegalDigitException(String message) {
        super(message);
    }
}


class BasedNumber {
    private int base;
    private int[] digits;

    BasedNumber(int base, int[] digits)throws IllegalBaseException{
        // check base and throw exception if it is not great than 1
        if(base<1)
            throw new IllegalBaseException("Base Should be > 1");
        //if the digit array is empty
        if(digits.length < 1)
            throw new IllegalDigitException("All digits must be in the range [0,n)");
        //if the digits is not within legal range (specified by the base)
        for(int digit : digits){
            if(digit>base || digit<0)
                throw new IllegalDigitException("All digits must be in the range [0,n)");
        }

        this.base = base;
        this.digits = digits;
    }
    int getBase() { return base; }
    int getDigit(int n) { return digits[n]; }

    int getValue() {
        int ret = 0;

        for(int i=0; i<digits.length; i++) {
            ret = ret * base + digits[i];
        }
        return ret;
    }

    boolean equals(BasedNumber that) {
        return getValue() == that.getValue();
    }

    @Override
    public String toString() {
        return "The value for Base = "+base+" and digits = "+ Arrays.toString(digits)+" is "+getValue();
    }
}

---------------------------------------------------------------------------

OUTPUT:

Enter base:
2
Enter a list of digits separated by space:
1 0 0 1
The value for Base = 2 and digits = [1, 0, 0, 1] is 9
Enter base:
16
Enter a list of digits separated by space:
99
All digits must be in the range [0,n)
Enter base:
16
Enter a list of digits separated by space:
9 9
The value for Base = 16 and digits = [9, 9] is 153
Enter base:
2
Enter a list of digits separated by space:

Digits must be integers
Enter base:
0
Enter a list of digits separated by space:
1 0 0
Base Should be > 1
Enter base:
3
Enter a list of digits separated by space:
d 5
Digits must be integers
Enter base:

Add a comment
Know the answer?
Add Answer to:
Output Enter base: 2 supply a list of digits separated by space: 1 0 0 1...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need the following written in Java please, thank you ' We want you to implement...

    I need the following written in Java please, thank you ' We want you to implement a java class that will show details on users and throw exceptions where needed. The following requirements specify what fields you are expected to implement in your User class: - A private String firstName that specifies the first name of the user - A private String lastName that specifies the last name of the user - A private int age that specifies user's age...

  • In this project, you are asked to design and implement a class for double link list...

    In this project, you are asked to design and implement a class for double link list to hold integers: – The class should be called DList, you also need a class called Node that contains an int as the data – Node needs the following data: int data; //the data held by the node Node* parent; //the parent of the Node Node* child; //the child of the Node – Node needs the following public functions: Node(int)// constructor to create a...

  • Please use Java only. Write a class, ZeroException, which is an Exception, and is used to signal...

    Please use Java only. Write a class, ZeroException, which is an Exception, and is used to signal that something is zero when it shouldn't be. -- Not needed Write the class ArrayManipulator which creates an array and provides several methods to manipulate values taken from an array. --needed ZeroException Task: -- Not needed Exceptions are used to signal many types of problems in a program. We can write our own as well to describe specific exceptional conditions which may arise....

  • Write a Lottery class that simulates a 6-number lottery (e.g. "Lotto"). The class should have an...

    Write a Lottery class that simulates a 6-number lottery (e.g. "Lotto"). The class should have an array of six integers named lotteryNumbers, and another array of six integers named userLotteryPicks. The class' constructor should use the Random class to generate a unique random number in the range of 1 to 60 for each of the 6 elements in the lotteryNumbers array. Thus, there should be a loop that keeps generating random numbers until all 6 numbers are unique.  The Lottery class...

  • You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an...

    You are to write a program (BookExceptionsDemo.java) that will create and, using user input, populate an array of instances of the class Book. The class Book is loaded in our Canvas files: Book.java The user will enter a number n (n must be > 0, trap the user until they input a valid value for n), Your program will declare and create an array of size n of instances of the class Book. The user will be asked to enter...

  • Java Please - Design and implement a class Triangle. A constructor should accept the lengths of...

    Java Please - Design and implement a class Triangle. A constructor should accept the lengths of a triangle’s 3 sides (as integers) and verify that the sum of any 2 sides is greater than the 3rd(i.e., that the 3 sides satisfy the triangle inequality). The constructor should mark the triangle as valid or invalid; do not throw an exception. Provide get and set methods for the 3 sides, and recheck for validity in the set methods. Provide a toString method...

  • C++ with comments please! // numberverifier.cpp #include <iostream> #include <exception> using std::cout; using std::cin; using std::endl;...

    C++ with comments please! // numberverifier.cpp #include <iostream> #include <exception> using std::cout; using std::cin; using std::endl; #include <cmath> #include <cstring> class nonNumber : public exception { public: /* write definition for the constructor */ -- Message is “An invalid input was entered” }; int castInput( char *s ) { char *temp = s; int result = 0, negative = 1; // check for minus sign if ( temp[ 0 ] == '-' ) negative = -1; for ( int i...

  • To use the digits function, enter 1 To use the average function, enter 2 To use the perfect sum f...

    use matlab To use the digits function, enter 1 To use the average function, enter 2 To use the perfect sum function, enter3 To exit the program, enter 4 Please select a number = 6 Please re-select again: 2 please enter the first number 3 please enter the second number: 6 please enter the third number: 3 The average equals to: 4 Write a function, called digits function that is able to calculate the number of digits and the summation...

  • Please help with this, and leave comments explainging the code you wrote, thank you for your...

    Please help with this, and leave comments explainging the code you wrote, thank you for your help Write a Lottery class that simulates a 6-number lottery (e.g. "Lotto"). The class should have an array of six integers named lotteryNumbers, and another array of six integers named userLotteryPicks. The class' constructor should use the Random class to generate a unique random number in the range of 1 to 60 for each of the 6 elements in the lotteryNumbers array. Thus, there...

  • i need help writing these programs in c++ format 1. Enter two integer arrays: array1-129, 0,...

    i need help writing these programs in c++ format 1. Enter two integer arrays: array1-129, 0, -56, 4, -7 and array2-19, 12, -36, -2, 12 3. Write the code to form and display another array array3 in which each element is the sum of numbers in the position in both arrays. Use pointers and functions: get array0. process arrays0 and show array0 (50 points) 2. Enter a positive 5-digit integer via the keyboard. Display each digit and fol- lowed by...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT