Contenido
Java Exception Handling (Try-catch)...................................................................................................2
Java Exception Handling.....................................................................................................................2
Java Factory Pattern...........................................................................................................................3
Java Method Overriding.....................................................................................................................3
Java Hashset.......................................................................................................................................3
Java Comparator.................................................................................................................................3
Java Exception Handling (Try-catch)
https://www.hackerrank.com/challenges/java-exception-handling-try-catch/problem
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
try{
Scanner scan=new Scanner(System.in);
int valA= scan.nextInt();
int valB=scan.nextInt();
System.out.println((valA/valB));
}catch(InputMismatchException e){
System.out.println(e.getClass().getName());
}catch(ArithmeticException e){
System.out.println(e);
}
}
}
Java Exception Handling
https://www.hackerrank.com/challenges/java-exception-handling/problem
class MyCalculator {
private static final String MSG_EXCEP_LESSS_ZERO="n or p should not be negative.";
private static final String MSG_EXCEP_EQUAL_ZERO="n and p should not be zero.";
public int power ( int n, int p) throws Exception{
if((n<0) || (p<0)){
throw new Exception(MSG_EXCEP_LESSS_ZERO);
}else if (n == 0 && p == 0) {
throw new Exception(MSG_EXCEP_EQUAL_ZERO);
}
return (int)Math.pow(n,p);
}
}
Java Factory Pattern
https://www.hackerrank.com/challenges/java-factory/problem
if (order.equals("cake"))
return new Cake();
else
return new Pizza();
Java Method Overriding
https://www.hackerrank.com/challenges/java-method-overriding/problem
@Override
void getNumberOfTeamMembers() {
System.out.println("Each team has 11 players in " + getName());
}
Java Hashset
https://www.hackerrank.com/challenges/java-hashset/problem
Set<String> setPairs = new HashSet<>();
for (int i = 0; i < t; i++) {
setPairs.add(pair_left[i] + " " + pair_right[i]);
System.out.println(setPairs.size());
}
Java Comparator
https://www.hackerrank.com/challenges/java-comparator/problem
HackerRank
class Checker implements Comparator<Player>{
@Override
public int compare(Player playerA, Player playerB) {
int resultScore = playerB.score - playerA.score;
if(resultScore == 0){
resultScore = playerA.name.compareTo(playerB.name);
}
return resultScore;
}
}