Question

JAVA PROG HW Problem 1 1. In the src −→ edu.neiu.p2 directory, create a package named...

JAVA PROG HW

Problem 1

1. In the src −→ edu.neiu.p2 directory, create a package named problem1. 2. Create a Java class named StringParser with the following:

  • ApublicstaticmethodnamedfindIntegerthattakesaStringandtwocharvariables as parameters (in that order) and does not return anything.

  • The method should find and print the integer value that is located in between the two characters. You can assume that the second char parameter will always follow the firstchar parameter. However, you cannot assume that the parameters will be different from each other. Print out the result in this format (where XX represents the integer value): Integer: XX

  • You may not use any loops, conditional statements, or regex (including switch state- ments and the tertiary operator).

1

  • You cannot assume that only valid integers or nothing will appear in between the specified characters. If the value is not valid or there is nothing in between the specified characters,printout"Invalid characters"followedbyprintingouttheresultofcalling the toString method on the exception object.

  • Hint: Think about the methods that you can use to convert Strings to integers and whether they throw exceptions! Make sure to handle the most specific exception class (i.e. do NOT use the superclass Exception to catch the exception object).

  1. Once you’ve created the method, run the StringParserTest class in the tests package to see if you’ve created the code correctly.

  2. Tohelpyourselfdebugandtestyourcode,createaJavaclassnamedStringParserDemothat has the main method. In the main method include at least three examples. Note that for the examples below, the method call is provided, followed by the expected output.

StringParser.findInteger("rugtsbckgus!32*", '!', '*'); Expected Output:
Integer: 32

StringParser.findInteger("rujfbgl&%fkslga", '&', '%'); Invalid integer
java.lang.NumberFormatException: For input string: ""

StringParser.findInteger("rusbdi#1038#jjdksu", '#', '#'); Integer: 1038

Problem 2

  1. In the src −→ edu.neiu.p2 directory, create a package named problem1.

  2. Create a Java class named Complement with the following:

    • A public static method named onesComplement that takes a String as a parameter and returns a String that is the 1’s complement of the parameter.

    • If the String is not a valid binary number (i.e. only has 0s and 1s), you should throw an IllegalArgumentException with the message "Not a valid binary number".

    • You may not use any loops.

    • You may use one conditional statement, but it cannot include any else if or else blocks.

  3. Once you’ve created the method, run the ComplementTest class in the tests package to see if you’ve created the code correctly.

  4. To help yourself debug and test your code, create a Java class named ComplementDemo that has the main method. In the main method include at least three examples.

Problem 3

Now let’s put everything together in an object-oriented manner! 2

  1. In the problem3 package, create a class named PositiveNumberStatistics that has the following:

    • A private double 1D array instance variable named numbers.

    • A constructor that takes one parameter, a 1D double array. The constructor should throw an IllegalArgumentException with the message "Array length of zero" if the parameter has a length of 0. If the exception is not thrown, the constructor should create the numbers array and copy every element from the parameter into the numbersinstance variable. However, if any of the elements are less than or equal to zero, the constructor should throw a NumberFormatException with the message "Non-positive value at index X" where X is the first index at which a non-positive value occurs.

    • A method named average that does not take any parameters and returns a double. The method should return the average of the numbers in the instance variable numbers. Note that you do not need to worry about whether the numbers instance variable has been created in this method because this method will only be usable if the constructor does not throw an exception.

  2. Onceyou’vecreatedthemethod,runthePositiveNumberStatisticsTestclassinthetestspackage to see if you’ve created the code correctly.

  3. Then, in the StatsDemo class in the problem3 folder, write the code to handle creating an object for each of the provided arrays in the main method and call the average method. You should handle any exceptions by printing out the result of calling the toString method on the exception object.

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

Solution 1

in this we cannot use any loops or conditional statement but waht we can use is indexOf() adn substring() methods of Java String class.
indexOf(char) -> returns first index of character in the string
indexof(char,int) -> return index of char in strign from index provided as second parameter
After we have the index of both the parameters we can use the Integer.parseInt() method on substring() from index1 to inde2 to get teh deisred output.
Code

public class StringParser{

    public static void findInteger(String str,char a,char b){

            //first index of characetr a

            int pos1=str.indexOf(a);

            //index of character b after postion of character a

            int pos2=str.indexOf(b,pos1+1);

            //now we apply parse method on teh substrign got

            //as per the above two indexes

            int num=Integer.parseInt(str.substring(pos1+1,pos2));

            System.out.println("Integer : "+num);

    }

  

    public static void main(String args[])

    {

        //uncomment to see output for others

        StringParser.findInteger("rugtsbckgus!32*", '!', '*');

        // StringParser.findInteger("rujfbgl&%fkslga", '&', '%');

        // StringParser.findInteger("rusbdi#1038#jjdksu", '#', '#');

      

    }

    

}

Output
StringParser.findInteger("rugtsbckgus!32*", '!', '*');

Solution 2

To solve this we can use the BigInteger class of Java which is in the java.math library
In order to check if the string has only 0 and 1 we can uses regex adn match method of java strign class as we can use one if sattement.

Code

import java.math.*;

public class Complement{

    

    public static String onesComplement(String a){

        //use regex to check if the string has any ther character except 0 or 1

        if(a.matches("[01]+")){

            int length = a.length();

            BigInteger b = BigInteger.ONE.shiftLeft(length + 1);

            String c = b.add(new BigInteger(a, 2).not()).toString(2);

            c = c.substring(c.length() - length);

            return c;

        }

        //throw  exception for any such number

        throw new IllegalArgumentException ("Not a valid binary number");

    }

    public static void main(String args[])

    {

        //uncomment to check other test casses

        System.out.println(onesComplement("1000"));

        // System.out.println(onesComplement("0001"));

        // System.out.println(onesComplement("102"));

    }

    

}

Output
For Input : onesComplement("1000")

Solution 3

This is a direct exception handling question. use try/catch blocks while calling the methods .

Code

public class PositiveNumberStatistics {

    

    //private memer variable

    private double numbers[];

    //constructor

    PositiveNumberStatistics(double num[]){

        //if array has no elements throw exception

        if(num.length==0)

            throw new IllegalArgumentException("Array length of zero");

        else{

            numbers=new double[num.length];

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

                if(num[i]<=0)

                    throw new NumberFormatException("Non-positive value at index "+i);

                else{

                    numbers[i]=num[i];

                }

            }

        }

    }

    //function to return the average of values in the private member variable

    public double average(){

        double sum=0;

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

            sum = sum + numbers[i];

        }

        return sum/numbers.length;

    }


    public static void main(String args[]){

        //test case 1

        try{

            double val[]={5,8};

            PositiveNumberStatistics p=new PositiveNumberStatistics(val);

            System.out.println("Average of {5,8} : "+p.average());

        }

        catch(Exception e){

            System.out.println("Average of {5,8} Exception : "+e.toString());

        }

        //test case 2

        try{

            double val[]={};

            PositiveNumberStatistics p=new PositiveNumberStatistics(val);

            System.out.println("Average of {} : "+p.average());

        }

        catch(Exception e){

            System.out.println("Average of {} Exception : "+e.toString());

        }

        //test case 3

        try{

            double val[]={5,-1};

            PositiveNumberStatistics p=new PositiveNumberStatistics(val);

            System.out.println("Average of {5,-1} : "+p.average());

        }

        catch(Exception e){

            System.out.println("Average of {5,-1} Exception : "+e.toString());

        }

    

    }

}

Output:


Add a comment
Know the answer?
Add Answer to:
JAVA PROG HW Problem 1 1. In the src −→ edu.neiu.p2 directory, create a package named...
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
  • Problem 1 1. In the src → edu.neiu.p2 directory, create a package named problem1. 2. Create...

    Problem 1 1. In the src → edu.neiu.p2 directory, create a package named problem1. 2. Create a Java class named StringParser with the following: • A public static method named findInteger that takes a String and two char variables as parameters (in that order) and does not return anything. • The method should find and print the integer value that is located in between the two characters. You can assume that the second char parameter will always follow the first...

  • put everything together in an object-oriented manner! create a class named PositiveNumberStatistics that has the following:...

    put everything together in an object-oriented manner! create a class named PositiveNumberStatistics that has the following: A private double 1D array instance variable named numbers. A constructor that takes one parameter, a 1D double array. The constructor should throw an IllegalArgumentException with the message "Array length of zero" if the parameter has a length of 0. If the exception is not thrown, the constructor should create the numbers array and copy every element from the parameter into the numbers instance...

  • Problem 1 1. In the src → edu.neiu.p2 → problem1 directory, create a Java class called...

    Problem 1 1. In the src → edu.neiu.p2 → problem1 directory, create a Java class called HW4P1 and add the following: • The main method. Leave the main method empty for now. • Create a method named xyzPeriod that takes a String as a parameter and returns a boolean. • Return true if the String parameter contains the sequential characters xyz, and false otherwise. However, a period is never allowed to immediately precede (i.e. come before) the sequential characters xyz....

  • Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB....

    Java -Create an interface and implement it In the murach.db package, create an interface named IProductDB. This interface should specify this abstract method: public abstract Product get(String productCode); Modify the ProductDB class so it implements the IProductDB interface. Write the code for the new ‘get’ method. Then remove the getProductByCode method. In the Main class, modify the code so it works with the new ProductDB class. This code should create an instance of the IProductDB interface like this: IProductDB db...

  • Programming 5_1: Create a Java class named <YourName>5_1 In this class create a main method...

    Programming 5_1: Create a Java class named <YourName>5_1 In this class create a main method, but for now leave it empty. Then write a Java method getAverage which takes an array of integers as it’s argument. The method calculate the average of all the elements in the array, and returns that average. The method should work for an array of integers of any length greater than or equal to one. The method signature is shown below: public static double getAverage(...

  • PART I: Create an abstract Java class named “Student” in a package named “STUDENTS”. This class...

    PART I: Create an abstract Java class named “Student” in a package named “STUDENTS”. This class has 4 attributes: (1) student ID: protected, an integer of 10 digits (2) student name: protected (3) student group code: protected, an integer (1 for undergraduates, 2 for graduate students) (4) student major: protected (e.g.: Business, Computer Sciences, Engineering) Class Student declaration provides a default constructor, get-methods and set-methods for the attributes, a public abstract method (displayStudentData()). PART II: Create a Java class named...

  • create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines....

    create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the method, check if the...

  • signature 1. Create a new NetBeans Java project. The name of the project has to be...

    signature 1. Create a new NetBeans Java project. The name of the project has to be the first part of the name you write on the test sheet. The name of the package has to be testo You can chose a name for the Main class. (2p) 2. Create a new class named Address in the test Two package. This class has the following attributes: city: String-the name of the city zip: int - the ZIP code of the city...

  • 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...

  • I've been assigned to create a new Java application called "CheckString" (without the quotation marks) according...

    I've been assigned to create a new Java application called "CheckString" (without the quotation marks) according to the following guidelines. ** Each method below, including main, should handle (catch) any Exceptions that are thrown. ** ** If an Exception is thrown and caught, print the Exception's message to the command line. ** Write a complete Java method called checkWord that takes a String parameter called word, returns nothing, and is declared to throw an Exception of type Exception. In the...

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