Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Java. In this exercise you\'re going to create two methods that deal with exc

ID: 3594101 • Letter: I

Question

In Java.

In this exercise you're going to create two methods that deal with exceptions. One of the methods is the main() method, which will call another method. If an exception is thrown in the other method, main() must deal with it. A finally statement will be included to indicate that the program has completed. The method that main() will call will be named reverse, and it will reverse the order of the characters in a string. If the string contains no characters, reverse will propagate an exception up to the main() method.   

1. Create a class called Propagate and a main() method, which will remain empty for now.

2. Create a method called reverse. It takes an argument of a String and returns a String.

3. In reverse, check whether the String has a length of 0 by using the String.length() method. If the length is 0, the reverse method will throw an exception.

4. Now include the code to reverse the order of the String. Because this isn't the main topic of this chapter, the reversal code has been provided, but feel free to try it on your own.

String reverseStr = "";

for( int i=s.length()-1;i>=0;--i) {

reverseStr += s.charAt(i);

}

return reverseStr;

5. Now in the mai() method you will attempt to call this method and deal with any potential exceptions. Additionally, you will include a finally statement that displays when main() has finished.

Explanation / Answer

Propagate.java

import java.util.Scanner;

public class Propagate {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

try{

System.out.println("Enter the String: ");

String s = scan.nextLine();

System.out.println("Reverse String: "+reverse(s));

} catch(Exception e) {

System.out.println("Exception occurred. "+e.toString());

} finally {

scan.close();

System.out.println("Thank you. Bye.");

}

}

public static String reverse(String s){

String reverseStr = "";

for( int i=s.length()-1;i>=0;--i) {

reverseStr += s.charAt(i);

}

return reverseStr;

}

}

Output:

Enter the String:
Hello How are you
Reverse String: uoy era woH olleH
Thank you. Bye.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote