Question

In: Computer Science

How can the classes be modified to satisfy the comments & example tester: public class InvalidIntegerException...

How can the classes be modified to satisfy the comments & example tester:

public class InvalidIntegerException extends Exception{

// Write a class for an InvalidIntegerException here

//Constructor that takes no arguments

public InvalidIntegerException (){

super(); }

//Constructor that takes a string message

public InvalidIntegerException (String message){

super(message); }

}

import java.io.InputStream;
import java.io.IOException;

public class Parser {
    private InputStream in;

    public static final int CHAR_ZERO = (int) '0';

    public Parser (InputStream in) {
        this.in = in;
    }

    // Complete the following method as described in the assignment

    public int readInt () {


        //read characters from the InputStream in (an instance variable for the Parser class).

        // Specifically, your method should read the successive characters from in until the next whitespace character or end of stream is encountered the method Character.isWhitespace(char ch) will probably be helpful here

        // If those characters constitute an integer—i.e., are all digits 0 through 9, possibly starting with the - character—then readInt() should return the int whose decimal representation corresponds to these characters.

        //If a non-numerical character is encountered, readInt() should do the following:

        //Continue reading from in until the next whitespace character is read or the end of the stream is reached.

        //Throw an InvalidIntegerException with a message indicating the first non-numerical character encountered in in.

    }

}

import java.io.InputStream;

import java.io.IOException;

public class ParserTester {

    public static void main (String[] args) {

        Parser p = new Parser(System.in);

        int    x = 0;

        // Modify the loop below so that the code also catches

        // InvalidIntegerExceptions and prints the appropriate error message: Could not read integer followed by the details of the caught exception.

        // InvalidIntegerException should not break out of the main loop in the program—after an InvalidIntegerException, the user should be able to continue entering more values.

        //Note that an InvalidIntegerException should not break out of the main loop in the program—after an InvalidIntegerException, the user should be able to continue entering more values.

        while (true) {

            try {

                System.out.print("Enter a number (-1 to exit): ");

                x = p.readInt();

                System.out.println("x = " + x);

                if (x == -1) {

                    System.out.println("Goodbye!");

                    return;

                }

            }

            catch (IOException e) {

                System.out.println("Reading error: " + e);

                return;

            }

        }

    }

}

When tested, for instance:

Enter a number (-1 to exit): 3857

x = 3857

Enter a number (-1 to exit): -4

x = -4

Enter a number (-1 to exit): 2m2

Could not read integer. InvalidIntegerException: Non-numerical character 'm' encountered.

Enter a number (-1 to exit): 13-4

Could not read integer. InvalidIntegerException: Non-numerical character '-' encountered.

Enter a number (-1 to exit): -ry24x

Could not read integer. InvalidIntegerException: Symbol '-' followed by non-numerical character 'r' encountered.

Enter a number (-1 to exit): 200

x = 200

Enter a number (-1 to exit): -1

x = -1

Goodbye!

Solutions

Expert Solution

Answer :

Code follows :

// ParserTester.java

import java.io.InputStream;
import java.io.IOException;

public class ParserTester {
public static void main (String[] args) {
Parser p = new Parser(System.in);
int x = 0;

// Modify the loop below so that the code also catches
// InvalidIntegerExceptions and prints the appropriate error message: Could not read integer followed by the details of the caught exception.
// InvalidIntegerException should not break out of the main loop in the program—after an InvalidIntegerException, the user should be able to continue entering more values.
//Note that an InvalidIntegerException should not break out of the main loop in the program—after an InvalidIntegerException, the user should be able to continue entering more values.

while (true) {
try {
System.out.print("Enter a number (-1 to exit): ");
x = p.readInt();
System.out.println("x = " + x);
if (x == -1) {
System.out.println("Goodbye!");
return;
}
}
catch (IOException e) {
System.out.println("Reading error: " + e);
return;
}
catch (InvalidIntegerException e) {
System.out.println("Could not read integer. " + e);
  
}
}
}
}

// Parser.java

import java.io.InputStream;
import java.io.IOException;

public class Parser {
private InputStream in;
public static final int CHAR_ZERO = (int) '0';

public Parser (InputStream in) {
this.in = in;
}

public int readInt () throws InvalidIntegerException, IOException {
//read characters from the InputStream in (an instance variable for the Parser class).
// Specifically, your method should read the successive characters from in until the next whitespace character or end of stream is encountered the method Character.isWhitespace(char ch) will probably be helpful here
// If those characters constitute an integer—i.e., are all digits 0 through 9, possibly starting with the - character—then readInt() should return the int whose decimal representation corresponds to these characters.
//If a non-numerical character is encountered, readInt() should do the following:
//Continue reading from in until the next whitespace character is read or the end of the stream is reached.
//Throw an InvalidIntegerException with a message indicating the first non-numerical character encountered in in.
int ch;
String s = "";
String badChar = "";
boolean firstch = true, firstminus = false;
  
while (true) {
ch = in.read ();
if (firstch) {
if ((Character.isDigit(ch)) || (ch == '-') ) {
if (ch == '-')
firstminus = true;
s += (char) ch;
firstch = false;
continue;
}
}
else {
if (Character.isDigit(ch)) {
s += (char) ch;
continue;
}
}
if ((ch == -1) || (Character.isWhitespace ((char) ch)) ) break;
if (badChar == "")
badChar += (char) ch;
}
if (badChar == "")
return (Integer.parseInt (s));
else if (firstminus)
throw (new InvalidIntegerException ("Symbol '-' followed by non numerical character '" + badChar + "' encountered."));
else
throw (new InvalidIntegerException ("Non numerical character '" + badChar + "' encountered."));
}
}


// Invalid integer exception
public class InvalidIntegerException extends Exception {
// Write a class for an InvalidIntegerException here
//Constructor that takes no arguments
  
public InvalidIntegerException (){
super();
  
}
  
//Constructor that takes a string message
public InvalidIntegerException (String message){
super(message);
  
}
}

I hope this answer is helpful to you. If you like the answer Please Upvote(Thums Up), I'm need of it, Thank you.


Related Solutions

How can the classes be modified to satisfy the comments: public class InvalidIntegerException extends Exception{    ...
How can the classes be modified to satisfy the comments: public class InvalidIntegerException extends Exception{     // Write a class for an InvalidIntegerException here     //Constructor that takes no arguments public InvalidIntegerException (){ super(); } //Constructor that takes a string message public InvalidIntegerException (String message){ super(message); } } import java.io.InputStream; import java.io.IOException; public class Parser { private InputStream in; public static final int CHAR_ZERO = (int) '0'; public Parser (InputStream in) { this.in = in; } // Complete the following...
Specifications: This project will have two data classes and a tester class. Design: Create a solution...
Specifications: This project will have two data classes and a tester class. Design: Create a solution for this programming task. You will need to have the following parts: Text file to store data between runs. Two classes that implement the given interfaces. You may add methods beyond those in the interfaces A tester class that tests all of the methods of the data classes. Here are the interfaces for your data classes: package project1; import java.util.ArrayList; public interface Person {...
Specifications: This project will have two data classes and a tester class. Design: Create a solution...
Specifications: This project will have two data classes and a tester class. Design: Create a solution for this programming task. You will need to have the following parts: Text file to store data between runs. Two classes that implement the given interfaces. You may add methods beyond those in the interfaces A tester class that tests all of the methods of the data classes. Here are the interfaces for your data classes: package project1; import java.util.ArrayList; public interface Person {...
In Java, please write a tester code. Here's my code: public class Bicycle {     public...
In Java, please write a tester code. Here's my code: public class Bicycle {     public int cadence; public int gear;   public int speed;     public Bicycle(int startCadence, int startSpeed, int startGear) {         gear = startGear;   cadence = startCadence; speed = startSpeed;     }     public void setCadence(int newValue) {         cadence = newValue;     }     public void setGear(int newValue) {         gear = newValue;     }     public void applyBrake(int decrement) {         speed -= decrement;    ...
Write an application with five classes Vehicle, Car, Bus, Truck, and Tester class with main method...
Write an application with five classes Vehicle, Car, Bus, Truck, and Tester class with main method in it. The following characteristics should be used: make, weight, height, length, maxSpeed, numberDoors, maxPassenges, isConvertable, numberSeats, maxWeightLoad, and  numberAxels. Characteristics that are applicable to all vehicles should be instance variables in the Vehicle class. The others should be in the class(s) where they belong. Class vehicle should have constructor that initializes all its data. Classes Car, Bus, and Truck will have constructors which will...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog { String catalog_name; ArrayList<Item> list; Catalog(String cs_Gift_Catalog) { list=new ArrayList<>(); catalog_name=cs_Gift_Catalog; } String getName() { int size() { return list.size(); } Item get(int i) { return list.get(i); } void add(Item item) { list.add(item); } } Thanks!
how to sorted the list from another class!!! example i have a class public meso public...
how to sorted the list from another class!!! example i have a class public meso public meso(string id) public hashmap<string, integer> neou{ this class print out b d e c a now create another class public mesono public mesono(hashmap<string, integer> nei) //want to sorted meso class print list to this class!! // print out a b c d e } ( -------Java------)   
Please add comments to this code! Item Class: import java.text.NumberFormat; public class Item {    private...
Please add comments to this code! Item Class: import java.text.NumberFormat; public class Item {    private String name;    private double price;    private int bulkQuantity;    private double bulkPrice;    /***    *    * @param name    * @param price    * @param bulkQuantity    * @param bulkPrice    */    public Item(String name, double price, int bulkQuantity, double bulkPrice) {        this.name = name;        this.price = price;        this.bulkQuantity = bulkQuantity;        this.bulkPrice = bulkPrice;   ...
IN JAVA PLEASE, USE COMMENTS Following the example of Circle class, design a class named Rectangle...
IN JAVA PLEASE, USE COMMENTS Following the example of Circle class, design a class named Rectangle to represent a rectangle. The class contains: • Two double data fields named width and height that specify the width and height of the rectangle. The default values are 1 for both width and height. • A no-arg constructor that creates a default rectangle. • A constructor that creates a rectangle with specified width and height • A method name getWidth() return the value...
I have three classes: class VolleyPlayer, class VolleyTeam and class TestDriver 1.class: public class VolleyPlayer implements...
I have three classes: class VolleyPlayer, class VolleyTeam and class TestDriver 1.class: public class VolleyPlayer implements Comparable<VolleyPlayer> { // instance variables - private String name; private int height; private boolean female; public VolleyPlayer(String name, int height, boolean female) { this.name = name; this.height = height; this.female = female; } public String toString() {    return (female ?"Female":"Male")+": "+name+" ("+height+" cm)"; } public boolean isFemale() {    return female; } public boolean isMale() {    return !female; } public int getHeight()...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT