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!
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...
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;   ...
Consider the following code: public class Bay extends Lake { public void method1() { System.out.println("Bay 1");...
Consider the following code: public class Bay extends Lake { public void method1() { System.out.println("Bay 1"); super.method2(); } public void method2() { System.out.println("Bay 2"); } } //********************************* class Pond { public void method2() { System.out.println("Pond 2"); } } //************************** class Ocean extends Bay { public void method2() { System.out.println("Ocean 2"); } } //********************************* class Lake extends Pond { public void method3() { System.out.println("Lake 3"); method2(); } } //**************************** class Driver { public static void main(String[] args) { Object var4 =...
Package pacman.score Class ScoreBoard Object ScoreBoard public class ScoreBoard extends Object ScoreBoard contains previous scores and...
Package pacman.score Class ScoreBoard Object ScoreBoard public class ScoreBoard extends Object ScoreBoard contains previous scores and the current score of the PacmanGame. A score is a name and value that a valid name only contains the following characters: A to Z a to z 0 to 9 and must have a length greater than 0. The value is a integer that is equal to or greater than 0. Implement this for Assignment 1 Constructor Summary Constructors Constructor Description ScoreBoard() Creates...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT