Question

In: Computer Science

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 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;

            }

        }

    }

}

Solutions

Expert Solution

Here is the solution to above problem in Java. Please read the code comments for more information

JAVA CODE

import java.io.InputStream;
import java.io.IOException;
import java.util.*;

class Parser {
private InputStream in;

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

public Parser()
{
  
}
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.
  
Scanner sc = new Scanner(System.in); //take input from User
char ch='_';
String integer="";
String input = sc.nextLine();
  
int index=0;
//repeat till space is not encountered
try {
while((ch!= ' ')&& index<input.length())
{
ch = input.charAt(index++);
//read the character
  
if(ch>='0'&&ch<='9') //if numeric value add to the string
integer+=ch;
else if(ch==' ') //if space encountered break
break;
else //if something else
throw new IOException("Invalid input " + ch);
}
//print the valid integer
return Integer.parseInt(integer);
  
} catch(IOException e) {
System.out.println(e.getMessage()); //print the failing character
return -1;
}
}
  

}


public class Main
{
public static void main(String [] args)
{
Parser p = new Parser();
int result=p.readInt();
if(result!=-1)
System.out.println("Integer is: " + result );
}
}

Screenshot of output


Related Solutions

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...
Consider the following classes: public class Clock extends Bear { public void method3() { System.out.println("Clock 3");...
Consider the following classes: public class Clock extends Bear { public void method3() { System.out.println("Clock 3"); } } public class Lamp extends Can { public void method1() { System.out.println("Lamp 1"); } public void method3() { System.out.println("Lamp 3"); } } public class Bear extends Can { public void method1() { System.out.println("Bear 1"); } public void method3() { System.out.println("Bear 3"); super.method3(); } } public class Can { public void method2() { System.out.println("Can 2"); method3(); } public void method3() { System.out.println("Can 3"); }...
If the class Parrot extends the class Bird, what can't be said about the classes? Select...
If the class Parrot extends the class Bird, what can't be said about the classes? Select one answer: A. The Parrot class has access to the Parrot methods B. The Parrot class has access to the Bird methods C. The Bird class has access to the Bird methods D. The Bird class has access to the Parrot methods
public class Mammal extends SeaCreature { public void method1() { System.out.println("warm-blooded"); } } public class SeaCreature...
public class Mammal extends SeaCreature { public void method1() { System.out.println("warm-blooded"); } } public class SeaCreature { public void method1() { System.out.println("creature 1"); } public void method2() { System.out.println("creature 2"); } public String toString() { return "ocean-dwelling"; } } public class Whale extends Mammal { public void method1() { System.out.println("spout"); } public String toString() { return "BIG!"; } } public class Squid extends SeaCreature { public void method2() { System.out.println("tentacles"); } public String toString() { return "squid"; } } What...
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!
Implement the Nickel class. Include Javadoc comments for the class, public fields, constructors, and methods of...
Implement the Nickel class. Include Javadoc comments for the class, public fields, constructors, and methods of the class. I have added the Javadoc comments but please feel free to format them if they are done incorrectly. public class Nickel implements Comparable { private int year; /** * The monetary value of a nickel in cents. */ public final int CENTS = 5; /** * Initializes this nickel to have the specified issue year. * * @param year * * @pre....
write the following programs: Ram.java, Truck.java, LandVehicle.java and Vehicle.java. public class Ram extends Truck { public...
write the following programs: Ram.java, Truck.java, LandVehicle.java and Vehicle.java. public class Ram extends Truck { public static void main(String[] args) { // your implementation } public Ram() { // your implementation } } public class Truck extends LandVehicle { public Truck() { // your implementation } public Truck(String s) { // your implementation } } public class LandVehicle extends Vehicle { public LandVehicle() { // your implementation } } public class Vehicle { public Vehicle() { // your implementation
public class Flight extends java.lang.Object This class represents a single flight within the travel agency system....
public class Flight extends java.lang.Object This class represents a single flight within the travel agency system. Constructor Summary Constructors Constructor and Description Flight(java.lang.String airline, int flightNum, java.lang.String from, java.lang.String to, java.util.Calendar leavesAt, java.util.Calendar arrives, double price) Creates a new flight leg in the system. Method Summary All Methods Instance Methods Concrete Methods Modifier and Type Method and Description double getPrice() Retrieves the price of this flight. java.lang.String toString() Retrieves a formatted string summarizing this Flight. Methods inherited from class java.lang.Object...
Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static...
Add comments to the following code: PeopleQueue.java import java.util.*; public class PeopleQueue {     public static void main(String[] args) {         PriorityQueue<Person> peopleQueue = new PriorityQueue<>();         Scanner s = new Scanner(System.in);         String firstNameIn;         String lastNameIn;         int ageIn = 0;         int count = 1;         boolean done = false;         System.out.println("Enter the first name, last name and age of 5 people.");         while(peopleQueue.size() < 5) {             System.out.println("Enter a person");             System.out.print("First Name: ");             firstNameIn...
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;   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT