Hiking around HackerRank — 06

Andrew Chen
6 min readAug 23, 2020

08/02/2020

Note:

  1. All problems are published by HackerRank, credit to HackerRank
  2. The solutions are coded by myself, and open source just for study.

Java Exception Handling (Try-catch)

Java Exception Handling (Try-catch), retrieved from https://www.hackerrank.com/challenges/java-exception-handling-try-catch/problem

Try-catch is a convenient way to catch errors in your code. The “try” would allow you to execute the code, while “catch” would display warning messages if there’s anything wrong. It seems this is a pretty straightforward question.

import java.io.*;
import java.util.*;
public class Solution { public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
try {
Scanner input = new Scanner(System.in);
int x = input.nextInt();
int y = input.nextInt();
System.out.println(x / y);
}
catch (ArithmeticException | InputMismatchException e) {
if (e instanceof ArithmeticException) {
System.out.println("java.lang.ArithmeticException: / by zero");
}
else {
System.out.println("java.util.InputMismatchException");
}
}
}
}

Remember the “instanceof” keyword we discussed before? Now we can use it to check different errors! And now, it is finished.

Java Exception Handling

Java Exception Handling, retrieved from https://www.hackerrank.com/challenges/java-exception-handling/problem

I’m sorry to say, I still followed my initial mindset and intended to use “System.out.println()” to display error messages, which proven to be stupidly wrong.

This is what my code looked like initially:

import java.util.Scanner;
class MyCalculator {
/*
* Create the method long power(int, int) here.
*/
public static int power(int n, int p) throws Exception {
if (n < 0 || p < 0) {
System.out.println("java.lang.Exception: n or p should not be negative.");
}
if ( n == 0 || p == 0) {
System.out.println("java.lang.Exception: n and p should not be zero.");
}
return (int) Math.pow(n, p);
}
}public class Solution {
public static final MyCalculator my_calculator = new MyCalculator();
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
while (in .hasNextInt()) {
int n = in .nextInt();
int p = in .nextInt();
try {
System.out.println(my_calculator.power(n, p));
} catch (Exception e) {
System.out.println(e);
}
}
}
}

No surprise, it failed.

After referring to this doc [1], I realized I was supposed o use “throw new Exception” in my script. And this is what it became:

import java.util.Scanner;
class MyCalculator {
/*
* Create the method long power(int, int) here.
*/
public int power(int n, int p) throws Exception {
if (n < 0 || p < 0) {
throw new Exception ("java.lang.Exception: n or p should not be negative.");
}
if ( n == 0 && p == 0) {
throw new Exception ("java.lang.Exception: n and p should not be zero.");
}
int result = (int) Math.pow(n, p);
return result;
}
}
public class Solution {
public static final MyCalculator my_calculator = new MyCalculator();
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
while (in .hasNextInt()) {
int n = in .nextInt();
int p = in .nextInt();
try {
System.out.println(my_calculator.power(n, p));
} catch (Exception e) {
System.out.println(e);
}
}
}
}

I was confident about this version, but it still failed (both two tests). What wrong with it?

Oops! What a stupid mistake! I should have used “else if” instead of “if” for the second statement! Let’s modify it!

import java.util.Scanner;
class MyCalculator {
/*
* Create the method long power(int, int) here.
*/
public int power(int n, int p) throws Exception{
int result;
if(n==0 && p==0){
throw new Exception("n and p should not be zero.");
}
else if(n<0 || p<0){
throw new Exception("n or p should not be negative.");
}
else {
result=(int)Math.pow(n,p);
return result;
}
}
}
public class Solution {
public static final MyCalculator my_calculator = new MyCalculator();
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
while (in .hasNextInt()) {
int n = in .nextInt();
int p = in .nextInt();
try {
System.out.println(my_calculator.power(n, p));
} catch (Exception e) {
System.out.println(e);
}
}
}
}

Awesome! It worked this time! Cheers!

8/21/2020

(After a long long break, I’m back…)

Java Anagram

Java Anagram, retrieved from https://www.hackerrank.com/challenges/java-anagrams/problem

Well, it does not look like a difficult one. I assume we can just check the frequency of each character in the word. However, if so, we need to loop through the words and check every character. Is there an easier way?

Hmm, maybe we can sort a string and compare them? I found this doc on GeeksforGeeks, and it is super beneficial [2]. After modification, my code is like this:

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Solution { static boolean isAnagram(String a, String b) {
// Complete the function

Boolean flag = false;
if(a != null && b != null) {
char tempArr1[] = a.toLowerCase().toCharArray();
char tempArr2[] = b.toLowerCase().toCharArray();
Arrays.sort(tempArr1);
Arrays.sort(tempArr2);
String newA = tempArr1.toString();
String newB = tempArr2.toString();
flag = newA.equals(newB);
}
return flag;
}
public static void main(String[] args) { Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}

I think it should work. However, it shows “Compilation error,” unfortunately. What happened?

The embarrassing fact is, I imported “java.util.Arrays” in my IDE, but this is not allowed in the console… Then, what should we do? I’m afraid that we must turn to loops to solve this one. Now, my code is as following:

import java.util.Scanner;public class Solution {    static boolean isAnagram(String a, String b) {
// Complete the function
int aLen = a.length();
int bLen = b.length();
a = a.toLowerCase();
b = b.toLowerCase();
if (aLen != bLen || aLen == 0 || bLen == 0) return false; int[] charFreq = new int[26]; for (int i = 0; i < aLen; i++){
int index1 = a.charAt(i) - 'a';
int index2 = b.charAt(i) - 'a';
charFreq[index1]++;
charFreq[index2]--;
}
for (int i = 0; i < 26; i++){
if (charFreq[i] != 0) return false;
}
return true;
}
public static void main(String[] args) { Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}

Fortunately, it worked this time! Obviously, this is not the most efficient method to solve this (IMO). But I’ve tried my best. Also, I searched on the Internet and found a YouTuber, as well as a programmer, Nick White. He used almost the same solution. I hope my solution would not be considered as a cheat, LOL.

Conclusion

It is a long break. In fact, I was occupied by other stuff, but it should not be an excuse. Practicing should be a daily job and we may enjoy it. Anyway, I will keep making progresses!

This is my repo:

Hope it help!

Or, you can follow me on Twitter! Happy coding!

References:

[1] Custom Checked Exception, Baeldung, retrieved from https://www.baeldung.com/java-new-custom-exception

[2] Sort a String in Java (2 Different Ways), retrieved from https://www.geeksforgeeks.org/sort-a-string-in-java-2-different-ways/

--

--