Question

In: Computer Science

String inputStr; double number; try {       inputStr = JOptionPane.showInputDialog(null,             "Please input a number.");      ...

String inputStr;
double number;

try
{
      inputStr = JOptionPane.showInputDialog(null,
            "Please input a number.");
      if (inputStr.equals(""))
            throw new IllegalArgumentException("Please enter a number");

      number = Double.parseDouble(inputStr);

      JOptionPane.showMessageDialog(null,
            "The square of the number is " + number * number);
}
catch (NumberFormatException e)
{
      JOptionPane.showMessageDialog(null,
            "Please enter a valid number to square");
}
catch (IllegalArgumentException e)
{
      JOptionPane.showMessageDialog(null,
            e.getMessage());
}
finally
{
      System.exit(0);
}

1) First,Why must the two catch blocks be listed in the order that they appear? What is the expected output if the user does not enter anything into the input dialog? What is the expected output if the user enters “ten” into the input dialog? And then-What is the purpose of the throw statement located within the try block? What is the purpose of the finally block at the end of the code? Now assume the user must enter only positive numbers. Provide a very brief example of a customly thrown exception when the user enters a negative number. Then,What is the relationship between binary files and performing a random file access? Given a binary file consisting of a sequence of integers (int in Java), how must the file pointer be managed to correctly move to the start of each integer? Then, Briefly describe the process of object serialization and object deserialization. And How would you determine the size of an object in bytes?

All parts must be answered for question 1 to receive any credit.

Solutions

Expert Solution

Why must the two catch blocks be listed in the order that they appear?

NumberFormatException is a sub class of IllegalArgumentException

If you will user IllegalArgumentException first then NumberFormatException,

it will never execute NumberFormatException because it will caught by IllegalArgumentException.

What is the expected output if the user does not enter anything into the input dialog?

It will display "Please enter a number" message

Because the condition inputStr.equals("") becomes true

What is the expected output if the user enters “ten” into the input dialog?

It will display message "Please enter a valid number to square"

Because while converting to double using Double.parseDouble(inputStr); will generate NumberFormatException.

What is the purpose of the throw statement located within the try block?

Will through an exception to it respective catch block.

In your case throw new IllegalArgumentException("Please enter a number"); statement will transfer the control to

following catch block:

catch (IllegalArgumentException e)
{
      JOptionPane.showMessageDialog(null,
            e.getMessage());
}

What is the purpose of the finally block at the end of the code?

If exception is generated control will transfer to respective catch block and then will execute finally block.

If exception is not generated will calculate and display the result and then will execute finally block.

Now assume the user must enter only positive numbers.

Assume user enters 3

then you will get the following output:

The square of the number is 9.0

Provide a very brief example of a customly thrown exception when the user enters a negative number.

if(number < 0)

throw new IllegalArgumentException("Please enter a positive number.");

If user will enter -3 then you will get the following message:

Please enter a positive number.

What is the relationship between binary files and performing a random file access?

1) In binary file there are two different methods of storing integers and floating-point numbers in memory, depending on the processor:

For 4-byte int (Example: 5E2):

The first of the four bytes in memory holds the most significant byte: 00 00 05 E2 (big-endian mechanism)

Otherwise start with the least significant byte values: E2 05 00 00

2) The writeInt() method of DataOutput interface writes an integer as a 4 - bytes binary quantity regardless of the number of digits to write.

The writeDouble() method of DataOutput interface writes a double as an 8 - bytes binary quantity regardless of the number.

Random access allows us to read or write data anywhere in a file.

Random access file provides a file pointer which indicates the position of the next byte to be read or write.

Given a binary file consisting of a sequence of integers (int in Java), how must the file pointer be managed to correctly move to the start of each integer?

Scanner keyboard = new Scanner(new File("Numbers.txt"));

int [] num = new int[200];

int counter = 0;

while(keyboard.hasNextInt())

num[counter++] = keyboard.nextInt();

Briefly describe the process of object serialization and object deserialization.

Serialization converts the object into byte stream, and also stores information about object type and the type of data stored in the object.

Where as De-serialization converts byte stream to actual object.

How would you determine the size of an object in bytes?

import java.lang.instrument.Instrumentation;

public class ObjectSize

{

private static volatile Instrumentation ins;

public static void premain(final String strArgs,

final Instrumentation inst)

{

ins = inst;

}

public static long getObjectSize(final Object obj)

{

return ins.getObjectSize(obj);

}

}

public class Demo

{

int x;

public static void main(String [] args)

{

System.out.println(

ObjectSize.getObjectSize(new Demo()));

}

}


Related Solutions

Write a driver to get a String input from keyboard and if the input string has...
Write a driver to get a String input from keyboard and if the input string has less than 10 characters, throw a StringTooShortException. public class StringTooShortException extends Exception {     //-----------------------------------------------------------------     // Sets up the exception object with a particular message.     //-----------------------------------------------------------------     public StringTooShortException()     {         super("String does not have enough characters");     } }
In this Exercise, you have to take a single string as input. Using this input string,...
In this Exercise, you have to take a single string as input. Using this input string, you have to create multiple queues in which each queue will comprise of separate word appeared in input string. At the end, you will again concatenate all queues to a single queue.s Example: String = “Data Structure and Algo” Q1 = D → a → t → a Q2 = S → t → r → u → c → t → u →...
PLEASE PROVIDE COMMENTS ON STEPS Write a C++ program that modifies a string (null terminated) as...
PLEASE PROVIDE COMMENTS ON STEPS Write a C++ program that modifies a string (null terminated) as follows: Consonants are positioned at the beginning of the string and vowels are moved to the end of the string. Example : Original string : washer New string : wshrae Note: The library string functions cannot be used. You must use pointers and the switch statement to execute this program. Assume that the vowels are a, e, i, o, and u. The modification has...
Write a program that takes its input from a file of number type double and outputs...
Write a program that takes its input from a file of number type double and outputs the average of the numbers in the file to the screen. The file contains nothing but numbers of the type double separated by blanks and/ or line breaks. If this is being done as a class assignment, obtain the file name from your instructor. File name: pr01hw05input.txt 78.0 87.5 98.1 101.0 4.3 17.2 78.0 14.5 29.6 10.2 14.2 60.7 78.3 89.3 29.1 102.3 54.1...
python 3 please Define a function voweliest that takes as input a string and returns as...
python 3 please Define a function voweliest that takes as input a string and returns as output a tuple where the string that has the most vowels in it is the first element and the second is the number of vowels in that string. Note: don't worry about ties or capital letters Hint: consider defining and using a separate function that counts the number of vowels in a given string
C++ Please Define a function named "isAscending" that accepts a string as an input parameter and...
C++ Please Define a function named "isAscending" that accepts a string as an input parameter and returns "true" if all the characters included in the string are ordered in ascending order of their ASCII codes or the input string is a null string, and returns "false" otherwise. For example, if the string "ABXab" is passed to the function, it returns "true" because the ASCII code of 'B' is greater than 'A', 'X' is greater than 'B', 'a' is greater than...
Given a string of at least 3 characters as input, if the length of the string...
Given a string of at least 3 characters as input, if the length of the string is odd return the character in the middle as a string. If the string is even return the two characters at the midpoint. -------------------------------------------------------------- public class Class1 { public static String midString(String str) {     //Enter code here } }
c++. please read this task carefully. First, try given examples of input to your code, if...
c++. please read this task carefully. First, try given examples of input to your code, if it works, then send it here. Create structure Applicants with following fields: struct applicants{ int id; string name; string surname; int subject1,subject2,subject3,selectedSubject; string specialCase; int total; }; SpecialCase (if applicant has "Awardee of Olympiads", then this field is "true", otherwise "false"). Do not forget that all "Awardees of Olympiads" will gain grants automatically. If the total points are same your algorithm have to choose...
Add the following private attributes: String publisher String title String ISBN String imageName double price Create...
Add the following private attributes: String publisher String title String ISBN String imageName double price Create getter/setter methods for all data types Create a constructor that takes in all attributes and sets them Remove the default constructor Override the toString() method and return a String that represents the book object that is formatted nicely and contains all information (attributes) In the main class: Create a main method that throws FileNotFoundException Import java.io libraries Import java.util.Scanner Create a loop to read...
Write a function that takes a C string as an input parameter and reverses the string.
in c++ Write a function that takes a C string as an input parameter and reverses the string. The function should use two pointers, front and rear. The front pointer should initially reference the first character in the string, and the rear pointer should initially reference the last character in the string. Reverse the string by swapping the characters referenced by front and rear, then increment front to point to the next character and decrement rear to point to the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT