How to Read Input From Standard Input Hackerrank Java
When executed, your completed code should print the following:
Generic Sports Each squad has n players in Generic Sports Soccer Class Each team has eleven players in Soccer Class
Solution:
class Sports { String getName() { return "Generic Sports"; } // Write your overridden getNumberOfTeamMembers method here void getNumberOfTeamMembers() { Organization.out.println("Each team has n players in " + getName()); } } course Soccer extends Sports { @Override Cord getName() { return "Soccer Course"; } } public grade JavaMethodOverriding { public static void main(String[] args) { Sports c1 = new Sports(); Soccer c2 = new Soccer(); System.out.println(c1.getName()); c1.getNumberOfTeamMembers(); Arrangement.out.println(c2.getName()); c2.getNumberOfTeamMembers(); } } 47. Challenge : Java Method Overriding 2
When a method in a bracket overrides a method in superclass, information technology is withal possible to call the overridden method usingsuperkeyword. If yous writesuper.func() to telephone call the functionfunc(), it will call the method that was divers in the superclass.
Y'all are given a partially completed lawmaking in the editor. Modify the code and so that the code prints the post-obit text:
Hello I am a motorcycle, I am a wheel with an engine. My antecedent is a cycle who is a vehicle with pedals. Solution:
grade BiCycle { String define_me() { render "a vehicle with pedals."; } } class Motorcycle extends Bicycle { String define_me() { return "a cycle with an engine."; } Motorbike() { System.out.println("Hullo I am a motorcycle, I am " + define_me()); String temp = super.define_me(); // Set this line System.out.println("My ancestor is a cycle who is " + temp); } } public course JavaMethodOverriding2SuperKeyword { public static void chief(String[] args) { new Motorcycle(); } } 48. Claiming : Java Instaneof Keyword
The Javainstanceof operator is used to test if the object or instance is an instanceof the specified type.
In this trouble we take given you three classes in the editor:
- Student form
- Rockstar grade
- Hacker class
In the main method, we populated anArrayList with several instances of these classes.count method calculates how many instances of each type is present in the ArrayList. The code prints three integers, the number of example of Educatee class, the number of case of Rockstar course, the number of instance of Hacker class.
Simply some lines of the code are missing, and you have to prepare it by modifying only3 lines! Don't add, delete or alter any extra line.
To restore the original code in the editor, click on the top left icon in the editor and create a new buffer.
Sample Input
5 Student Pupil Rockstar Educatee Hacker Sample Output
3 1 1 Solution:
class Educatee { } class Rockstar { } class Hacker { } public class JavaInstanceofkeyword { static Cord count(ArrayList mylist) { int a = 0, b = 0, c = 0; for (int i = 0; i < mylist.size(); i++) { Object element = mylist.become(i); if (element instanceof Student) a++; if (element instanceof Rockstar) b++; if (element instanceof Hacker) c++; } String ret = Integer.toString(a) + " " + Integer.toString(b) + " " + Integer.toString(c); return ret; } public static void chief(String[] args) { ArrayList mylist = new ArrayList(); Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int i = 0; i < t; i++) { String s = sc.next(); if (southward.equals("Student")) mylist.add(new Educatee()); if (s.equals("Rockstar")) mylist.add(new Rockstar()); if (southward.equals("Hacker")) mylist.add(new Hacker()); } System.out.println(count(mylist)); sc.close(); } } 49. Challenge : Coffee Iterator
Java Iterator class can aid y'all to iterate through every chemical element in a collection. Hither is a simple example:
import java.util.* ; public class Example { public static void principal ( String [] args ){ ArrayList mylist = new ArrayList (); mylist . add ( "Hello" ); mylist . add ( "Coffee" ); mylist . add ( "4" ); Iterator it = mylist . iterator (); while ( it . hasNext ()){ Object element = it . next (); System . out . println (( Cord ) chemical element ); } } } In this trouble you demand to complete a methodfunc. The method takes anArrayList as input. In thatArrayList at that place is i or more integer numbers, then at that place is a special string "###", after that there are one or more other strings. A sampleArrayListmay look like this:
element[0]=>42 element[1]=>10 element[two]=>"###" element[3]=>"Hello" element[four]=>"Java" You have to modify thefunc method by editingat most 2 lines then that the code simply prints the elements afterward the special string "###". For the sample above the output will be:
Hello Java Notation: The stdin doesn't contain the string"###", information technology is added in themain method.
To restore the original code in the editor, click the acme left icon on the editor and create a new buffer.
Solution:
public class JavaIterator { static Iterator func(ArrayList mylist) { Iterator it = mylist.iterator(); while (it.hasNext()) { Object element = it.next(); if (element instanceof String)// Hints: apply instanceof operator break; } render it; } @SuppressWarnings({ "unchecked" }) public static void main(Cord[] args) { ArrayList mylist = new ArrayList(); Scanner sc = new Scanner(System.in); int north = sc.nextInt(); int m = sc.nextInt(); for (int i = 0; i < north; i++) { mylist.add(sc.nextInt()); } mylist.add together("###"); for (int i = 0; i < m; i++) { mylist.add(sc.next()); } Iterator it = func(mylist); while (information technology.hasNext()) { Object element = it.next(); System.out.println((String) element); } sc.shut(); } } l. Challenge : Java Exception Handling (Try-Catch)
Exception handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or infrequent atmospheric condition requiring special processing – oft changing the normal flow of plan execution. (Wikipedia)
Java has congenital-in mechanism to handle exceptions. Using theendeavor argument we can test a cake of code for errors. Thecatchblock contains the code that says what to do if exception occurs.
This problem will test your knowledge on try-catch block.
You volition be given two integersx andy every bit input, you have to computeten/y . Iften andy are not32 fleck signed integers or ify is zero, exception will occur and y'all take to report information technology. Read sample Input/Output to know what to report in case of exceptions.
Sample Input 0:
ten 3 Sample Output 0:
3 Sample Input ane:
ten Hello Sample Output one:
coffee.util.InputMismatchException Sample Input ii:
x Sample Output 2:
java.lang.ArithmeticException: / by zero Sample Input 3:
23.323 Sample Output 3:
coffee.util.InputMismatchException
Solution:
public class JavaExceptionHandlingTryCatch { public static void primary(String[] args) { Scanner sc = new Scanner(Organisation.in); try { int x = sc.nextInt(); int y = sc.nextInt(); int z = x / y; System.out.println(z); } catch (ArithmeticException e) { System.out.println(e); } catch (InputMismatchException e) { System.out.println(e.getClass().getName()); } finally { sc.shut(); } } } 51. Challenge : Java Varargs – Simple Addition
Yous are given a courseSolution and itsmain method in the editor.
Your task is to create the classAdd together and the required methods so that the code prints thesum of the numbers passed to the officeadd together.
Note: Youradd together method in theAdd grade must impress thesum equally given in theSample Output
Input Format
There are six lines of input, each containing an integer.
Output Format
In that location will be only iv lines of output. Each line contains the sum of theintegers passed equally the parameters toadd in themainmethod.
Sample Output
ane+2=three ane+2+3=6 one+2+iii+4+5=15 1+2+3+iv+v+vi=21
Solution:
public class JavaVarargsSimpleAddition { public void add(int... a) { String b = ""; int c = 0; for (int i : a) { b += i + "+"; c += i; } Organization.out.impress(b.substring(0, b.length() - i)); Organization.out.println("=" + c); } } 52. Challenge : Coffee Reflection – Attributes
Coffee reflection is a very powerful tool to inspect the attributes of a class in runtime. For example, we can retrieve the list of public fields of a course usinggetDeclaredMethods().
In this problem, you will exist given a classSolution in the editor. Y'all have to fill up in the incompleted lines so that it prints all the methods of another class calledStudent in alphabetical order. Nosotros will append your code with theStudent class earlier running it. TheStudent class looks like this:
class Student { private String proper name ; private String id ; private Cord e-mail ; public String getName () { return proper noun ; } public void setId ( String id ) { this . id = id ; } public void setEmail ( String electronic mail ) { this . email = email ; } public void anothermethod (){ } ...... ...... some more methods ...... } You have to print all the methods of the pupil class in alphabetical order like this:
anothermethod getName setEmail setId ...... ...... some more methods ...... At that place is no sample input/output for this problem. If y'all press "Run Lawmaking", it will compile information technology, but it won't show any outputs.
Hint: See the oracle docs for more details about JAVA Reflection Methods and Fields
Solution:
class Educatee { private String proper noun; private String id; private String email; public String getName() { return proper noun; } public void setId(String id) { this.id = id; } public void setEmail(String email) { this.email = e-mail; } public void anothermethod() { } } public course JavaReflectionAttributes { public static void main(String[] args) { Class educatee = new Educatee().getClass(); Method[] methods = student.getDeclaredMethods(); ArrayList<Cord> methodList = new ArrayList<>(); for (Method m : methods) { methodList.add(m.getName()); } Collections.sort(methodList); for (String proper name : methodList) { Organization.out.println(proper noun); } } } 53. Challenge : Can yous Access?
You are given a classSolution and an inner classInner.Private. The chief method of classSolution takes an integernum as input. Thepowerof2 in courseInner.Private checks whether a number is a power ofii . You have to call the methodpowerof2 of the courseInner.Individual from themain method of the classSolution.
Constraints
ane ≤ num ≤ 230
Sample Output
8 is power of two An case of class: Solution.Inner.Private has been created
Solution:
public grade CanYouAccess { public static void primary(Cord[] args) throws Exception { DoNotTerminate.forbidExit(); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int num = Integer.parseInt(br.readLine().trim()); Object o;// Must be used to hold the reference of the instance of the class // Solution.Inner.Individual // Inner i= new Inner(); // Private p=new Individual(); /**master code starts from here*/ CanYouAccess.Inner si = new CanYouAccess.Inner(); o = si.new Private(); Organization.out.println(num + " is " + ((CanYouAccess.Inner.Individual) o).powerof2(num)); /**main code cease hither*/ System.out.println("An instance of class: " + o.getClass().getCanonicalName() + " has been created"); } // end of try catch (DoNotTerminate.ExitTrappedException e) { System.out.println("Unsuccessful Termination!!"); } }// end of main static class Inner { private class Private { private String powerof2(int num) { return ((num & num - ane) == 0) ? "power of ii" : "not a ability of 2"; } } }// end of Inner }// end of Solution class DoNotTerminate { // This class prevents exit(0) public static class ExitTrappedException extends SecurityException { private static final long serialVersionUID = 1L; } public static void forbidExit() { final SecurityManager securityManager = new SecurityManager() { @Override public void checkPermission(Permission permission) { if (permission.getName().contains("exitVM")) { throw new ExitTrappedException(); } } }; Organisation.setSecurityManager(securityManager); } } 54. Challenge : Java Mill Pattern
According to Wikipedia, a factory is simply an object that returns another object from some other method telephone call, which is assumed to exist "new".
In this problem, you are given an interfaceNutrient. At that place are two classesPizza andCake which implement theFood interface, and they both contain a methodgetType().
The main part in theMain class creates an instance of theFoodFactory grade. TheFoodFactory class contains a methodgetFood(String) that returns a new instance ofPizza orCake according to its parameter.
You are given the partially completed lawmaking in the editor. Please complete theFoodFactory form.
Sample Input i
cake Sample Output 1
The factory returned form Cake Someone ordered a Dessert! Sample Input 2
pizza Sample Output two
The factory returned course Pizza Someone ordered Fast Food!
Solution:
interface Food { public Cord getType(); } form Pizza implements Food { public Cord getType() { render "Someone ordered a Fast Food!"; } } grade Cake implements Food { public String getType() { render "Someone ordered a Dessert!"; } } class FoodFactory { public Nutrient getFood(String order) { /** * main code starts from here */ if (society.equalsIgnoreCase("Pizza")) { return new Pizza(); } else if (order.equalsIgnoreCase("Block")) { render new Cake(); } return naught; /** main code end herer */ }// End of getFood method }// End of manufacturing plant class public class JavaFactoryPattern { public static void main(String args[]) { Do_Not_Terminate.forbidExit(); Scanner sc = zip; try { sc = new Scanner(System.in); // creating the factory FoodFactory foodFactory = new FoodFactory(); // factory instantiates an object Food food = foodFactory.getFood(sc.nextLine()); System.out.println("The mill returned " + food.getClass()); System.out.println(food.getType()); } grab (Do_Not_Terminate.ExitTrappedException e) { System.out.println("Unsuccessful Termination!!"); } finally { sc.shut(); } } } class Do_Not_Terminate { public static class ExitTrappedException extends SecurityException { individual static final long serialVersionUID = 1L; } public static void forbidExit() { concluding SecurityManager securityManager = new SecurityManager() { @Override public void checkPermission(Permission permission) { if (permission.getName().contains("exitVM")) { throw new ExitTrappedException(); } } }; System.setSecurityManager(securityManager); } } 55. Challenge : Coffee Singleton Pattern
"The singleton pattern is a design pattern that restricts the instantiation of a grade to one object. This is useful when exactly one object is needed to coordinate actions across the organization."
– Wikipedia: Singleton Pattern
Consummate theSingleton class in your editor which contains the post-obit components:
- Aprivate Singleton non parameterized constructor.
- Apublic String instance variable named.
- Write astatic method namedgetSingleInstance that returns the single example of theSingleton class.
Once submitted, our subconsciousSolution class will check your lawmaking by taking a String as input so using yourSingleton class to print a line.
Input Format
You volition not be treatment whatsoever input in this challenge.
Output Format
Yous will not be producing any output in this challenge.
Sample Output
Hi I am a singleton! Let me say howdy earth to you
Solution:
public class JavaSingletonPattern { public String str = ""; private static final JavaSingletonPattern instance=zilch; private JavaSingletonPattern() { } public static JavaSingletonPattern getSingleInstance() { if (example == zero) return new JavaSingletonPattern(); render instance; } } 56. Challenge : Covariant Return Types
Java allows for Covariant Return Types, which means you tin can vary your return type as long you are returning a subclass of your specified return blazon.
Method Overriding allows a bracket tooverride the behavior of an existing superclass method and specify a return blazon that is some subclass of the original return type. It is all-time practice to use the@Override annotation when overriding a superclass method.
Implement the classes and methods detailed in the diagram below:
You will be given a partially completed code in the editor where theprimary method takes the name of a state (i.due east.,WestBengal, orAndhraPradesh) and prints the national flower of that country using the classes and methods written by yous.
Note:Do not utilise access modifiers in your class declarations.
Resources
Covariant Return Type
Java Covariant Type
Input Format
The locked code reads a unmarried string denoting the name of a subclass ofLand (i.e.,WestBengal,Karnataka, orAndhraPradesh), then tests the methods associated with that subclass. You are not responsible for reading whatever input from stdin.
Output Format
Output is handled for you lot by the locked code, which creates the object respective to the input string'due south class name and and then prints the proper name returned past that class' national flower'swhatsYourName method. You lot are not responsible for press anything to stdout.
Sample Output 0
Lily
Solution:
public class CovariantReturnTypes { /** * chief code starts from here** */ class Bloom{ public String whatsYourName(){ return "I have many names and types."; } } course Jasmine extends Flower{ public Cord whatsYourName(){ return "Jasmine"; } } class Lily extends Flower{ public String whatsYourName(){ return "Lily"; } } class Lotus extends Flower{ public Cord whatsYourName(){ return "Lotus"; } } course State{ Flower yourNationalFlower(){ return new Bloom(); } } grade WestBengal extends Land{ Jasmine yourNationalFlower(){ render new Jasmine(); } } class Karnataka extends State{ Lotus yourNationalFlower(){ return new Lotus(); } } class AndhraPradesh extends State{ Lily yourNationalFlower(){ return new Lily(); } /** * main code ends here */ } } 57. Challenge : Prime Checker
You are given a classSolution and itsmaster method in the editor. Your task is to create a coursePrime. The classPrime should contain a single methodcheckPrime.
The locked lawmaking in the editor will phone call thecheckPrime method with one or more than integer arguments. Y'all should write thecheckPrime method in such a mode that the lawmaking prints only the prime numbers.
Please read the code given in the editor advisedly. Also delight do not use method overloading!
Annotation: You may get a compile time error in this problem due to the statement below:
BufferedReader br=new BufferedReader(new InputStreamReader(in)); This was added intentionally, and y'all have to figure out a manner to get rid of the error.
Input Format
At that place are only five lines of input, each containing one integer.
Output Format
There will be only four lines of output. Each line contains but prime number numbers depending upon the parameters passed tocheckPrime in theprimary method of the classSolution. In case there is no prime, and then a blank line should exist printed.
Sample Output
2 2 2 3 2 3 5
Solution:
public class PrimeChecker { public void checkPrime(int... num) { String str = ""; for (int n : num) { boolean constitute = true; if (n <= three && due north > one) { str += n + " "; } else { for (int i = 2; i <= Math.sqrt(n); i++) { if (northward % i == 0) { found = imitation; break; } } if (constitute && n != 1) { str += north + " "; } } } System.out.println(str); } } 58. Challenge : Java Annotations
Java annotation tin be used to define the metadata of a Java form or form element. We can utilize Coffee annotation at the compile fourth dimension to instruct the compiler about the build process. Annotation is also used at runtime to go insight into the backdrop of class elements.
Java annotation tin can exist added to an element in the following manner:
@Entity Class DemoClass { } We can also set a value to the annotation member. For example:
@Entity ( EntityName = "DemoClass" ) Class DemoClass { } In Java, in that location are several congenital-in annotations. You can also define your ain annotations in the post-obit manner:
@Target ( ElementType . METHOD ) @Retentivity ( RetentionPolicy . RUNTIME ) @interface FamilyBudget { String userRole () default "GUEST" ; } Here, nosotros define an annotationFamilyBudget , whereuserRole is the simply member in that custom annotation. The userRoletakes butString blazon values, and the default is"Guest". If nosotros do not ascertain the value for this annotation member, then information technology takes the default. By using@Target, we tin specify where our annotation tin can be used. For case, the FamilyBudget annotation can only be used with the method in a class.@Retentivity defines whether the annotation is available at runtime. To learn more virtually Coffee annotation, y'all can read the tutorial and oracle docs.
Take a look at the post-obit code segment:
@Target ( ElementType . METHOD ) @Retention ( RetentionPolicy . RUNTIME ) @interface FamilyBudget { String userRole () default "GUEST" ; } class FamilyMember { public void seniorMember ( int upkeep , int moneySpend ) { Arrangement . out . println ( "Senior Member" ); System . out . println ( "Spend: " + moneySpend ); System . out . println ( "Budget Left: " + ( budget - moneySpend )); } public void juniorUser ( int budget , int moneySpend ) { System . out . println ( "Junior Member" ); System . out . println ( "Spend: " + moneySpend ); Organisation . out . println ( "Upkeep Left: " + ( budget - moneySpend )); } } public class Solution { public static void main ( String [] args ) { Scanner in = new Scanner ( Organisation . in ); int testCases = Integer . parseInt ( in . nextLine ()); while ( testCases > 0 ) { String role = in . next (); int spend = in . nextInt (); try { Class annotatedClass = FamilyMember . class ; Method [] methods = annotatedClass . getMethods (); for ( Method method : methods ) { if ( method . isAnnotationPresent ( FamilyBudget . class )) { FamilyBudget family = method . getAnnotation ( FamilyBudget . class ); String userRole = family unit . userRole (); int budgetLimit = family . budgetLimit (); if ( userRole . equals ( role )) { if ( spend <= budgetLimit ){ method . invoke ( FamilyMember . form . newInstance (), budgetLimit , spend ); } else { System . out . println ( "Budget Limit Over" ); } } } } } catch ( Exception e ) { east . printStackTrace (); } testCases --; } } } Here, we partially define an annotation,FamilyBudget and a form,FamilyMember . In this problem, we give the user role and the corporeality of coin that a user spends as inputs. Based on the user role, yous have to call the advisable method in the FamilyMember form. If the amount of coin spent is over the budget limit for that user part, information technology printsBudget Limit Over.
Your task is to consummate the FamilyBudget notation and the FamilyMember class so that theSolution class works perfectly with the defined constraints.
Note: You must complete the5 incomplete lines in the editor. You are not immune to change, delete or modify any other lines. To restore the original code, click on the top-left push button on the editor and create a new buffer.
Input Format
The get-go line of input contains an integerDue north representing the total number of examination cases. Each examination instance contains a string and an integer separated by a space on a single line in the following format:
UserRole MoneySpend Constraints
two ≤ Due north ≤ 10
0 ≤ MoneySpend ≤ 200
|UserRole| = 6
Name contains simply lowercase English letters.
Output Format
Based on the user role and upkeep outputs, output the contents of the certain method. If the amount of coin spent is over the budget limit, then outputBudget Limit Over.
Sample Input
3 SENIOR 75 Inferior 45 SENIOR forty Sample Output
Senior Fellow member Spend: 75 Upkeep Left: 25 Junior Member Spend: 45 Budget Left: 5 Senior Member Spend: twoscore Budget Left: 60
Solution:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface FamilyBudget { String userRole() default "Invitee"; int moneySpend() default 100; } grade FamilyMember { @FamilyBudget(userRole = "SENIOR") public void seniorMember(int budget, int moneySpend) { Arrangement.out.println("Senior Member"); Organisation.out.println("Spend: " + moneySpend); System.out.println("Upkeep Left: " + (budget - moneySpend)); } @FamilyBudget(userRole = "Junior", moneySpend = fifty) public void juniorUser(int upkeep, int moneySpend) { System.out.println("Inferior Fellow member"); Arrangement.out.println("Spend: " + moneySpend); System.out.println("Budget Left: " + (budget - moneySpend)); } } public course JavaAnnotations { public static void main(String[] args) { Scanner in = new Scanner(Organization.in); int testCases = Integer.parseInt(in.nextLine()); while (testCases > 0) { Cord office = in.side by side(); int spend = in.nextInt(); endeavor { Course annotatedClass = FamilyMember.class; Method[] methods = annotatedClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(FamilyBudget.course)) { FamilyBudget family = method.getAnnotation(FamilyBudget.class); Cord userRole = family.userRole(); int budgetLimit = family.moneySpend(); if (userRole.equals(role)) { if (budgetLimit >= spend) { method.invoke(FamilyMember.class.newInstance(), budgetLimit, spend); } else { Organization.out.println("Budget Limit Over"); } } } } } catch (Exception e) { e.printStackTrace(); } testCases--; } in.shut(); } } 59. Claiming : Coffee Lambda Expressions
This Java 8 challenge tests your noesis of Lambda expressions!
Write the following methods thatreturn a lambda expression performing a specified action:
- PerformOperation isOdd(): The lambda expression must rendertrue if a number is odd orfalse if information technology is even.
- PerformOperation isPrime(): The lambda expression must returntrue if a number is prime or false if it is composite.
- PerformOperation isPalindrome(): The lambda expression must returntrue if a number is a palindrome or faux if it is not.
Input Format
Input is handled for yous by the locked stub code in your editor.
Output Format
The locked stub code in your editor will impress T lines of output.
Sample Input
The first line contains an integer, T (the number of exam cases).
The T subsequent lines each depict a test case in the class of2 space-separated integers:
The showtime integer specifies the condition to check for (1 for Odd/Even,ii for Prime number, or3 for Palindrome). The second integer denotes the number to exist checked.
5 1 iv 2 5 3 898 ane three two 12 Sample Output
Fifty-fifty Prime PALINDROME ODD COMPOSITE
Solution:
interface PerformOperation { boolean check(int a); } grade MyMath { public static boolean checker(PerformOperation p, int num) { return p.check(num); } // Write your code here public static PerformOperation isOdd() { return n -> ((n & 1) == 1); } public static PerformOperation isPrime() { return north -> { if (due north < two) { return false; } else { int thousand = (int) Math.sqrt(n); for (int i = 2; i <= one thousand; i++) { if (northward % i == 0) return false; } render true; } }; } public static PerformOperation isPalindrome() { return n -> { String org = n + ""; String newString = new StringBuffer(org).reverse().toString(); return org.equals(newString); }; } } public class JavaLambdaExpressions { public static void principal(String[] args) throws IOException { MyMath ob = new MyMath(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); PerformOperation op; boolean ret = faux; String ans = nada; while (T-- > 0) { Cord southward = br.readLine().trim(); StringTokenizer st = new StringTokenizer(due south); int ch = Integer.parseInt(st.nextToken()); int num = Integer.parseInt(st.nextToken()); if (ch == 1) { op = ob.isOdd(); ret = ob.checker(op, num); ans = (ret) ? "ODD" : "EVEN"; } else if (ch == 2) { op = ob.isPrime(); ret = ob.checker(op, num); ans = (ret) ? "PRIME" : "COMPOSITE"; } else if (ch == three) { op = ob.isPalindrome(); ret = ob.checker(op, num); ans = (ret) ? "PALINDROME" : "NOT PALINDROME"; } System.out.println(ans); } } } threescore. Claiming : Coffee MD5
MD5 (Message-Digest algorithm v) is a widely-used cryptographic hash office with a128 -fleck hash value. Hither are some common uses forMD5:
- To store a ane-way hash of a password.
- To provide some assurance that a transferred file has arrived intact.
MD5 is one in a series of message assimilate algorithms designed by Professor Ronald Rivest of MIT (Rivest,1994 ); however, the security ofMD5 has been severely compromised, most infamously by the Flame malware in2012 . TheCMU Software Engineering science Constitute essentially considersMD5 to be "cryptographically broken and unsuitable for further use".
Given an alphanumeric string,south , denoting a password, compute and print itsMD5 encryption value.
Input Format
A single alphanumeric string cogents .
Constraints
-
six ≤ |s| ≤ 20
- Stringsouthward consists of English language alphabetic messages (i.due east.,[a – zA – Z] and/or decimal digits (i.e.,0 through9 ) simply.
Output Format
Print theMD5 encryption value ofs on a new line.
Sample Input 0
HelloWorld Sample Output 0
68e109f0f40ca72a15e05cc22786f8e6 Sample Input one
Javarmi123 Sample Output ane
2da2d1e0ce7b4951a858ed2d547ef485
Solution:
public class JavaMD5 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String southward = sc.side by side(); System.out.println(getMD5(s)); sc.close(); } private static Cord getMD5(Cord due south) { StringBuffer sb = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] result = md.digest(s.getBytes()); for (int i = 0; i < result.length; i++) { String hex = Integer.toHexString(0xff & result[i]); if (hex.length() == 1) sb.append('0'); sb.suspend(hex); } } grab (NoSuchAlgorithmException east) { // TODO Automobile-generated take hold of block e.printStackTrace(); } return sb.toString(); } } 61. Challenge : Coffee SHA-256
Cryptographic hash functions are mathematical operations run on digital information; by comparing the computedhash (i.eastward., the output produced past executing a hashing algorithm) to a known and expected hash value, a person can make up one's mind the information's integrity. For example, computing the hash of a downloaded file and comparing the event to a previously published hash issue tin show whether the download has been modified or tampered with. In add-on, cryptographic hash functions are extremely collision-resistant; in other words, it should be extremely difficult to produce the same hash output from two unlike input values using a cryptographic hash part.
Secure Hash Algorithm 2 (SHA-ii) is a set of cryptographic hash functions designed by the National Security Bureau (NSA). It consists of vi identical hashing algorithms (i.e.,SHA-256,SHA-512,SHA-224,SHA-384,SHA-512/224,SHA-512/256) with a variable digest size.SHA-256 is a256 -bit (32 byte) hashing algorithm which tin calculate a hash lawmaking for an input of upwards to264 – one $.25. Information technology undergoes64 rounds of hashing and calculates a hash code that is a 64 -digit hexadecimal number.
Given a string,s , impress itsSHA-256 hash value.
Input Format
A unmarried alphanumeric string denotings .
Constraints
-
half-dozen ≤ |s| ≤ 20
- Strings consists of English alphabetic letters (i.e.,[a – zA – Z] and/or decimal digits (i.eastward.,0 throughnine ) only.
Output Format
Print theSHA-256 encryption value ofs on a new line.
Sample Input 0
HelloWorld Sample Output 0
872e4e50ce9990d8b041330c47c9ddd11bec6b503ae9386a99da8584e9bb12c4 Sample Input one
Javarmi123 Sample Output 1
f1d5f8d75bb55c777207c251d07d9091dc10fe7d6682db869106aacb4b7df678
Solution:
public class JavaSHA256 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.side by side(); System.out.println(getSHAHEX(due south)); sc.shut(); } private static Cord getSHAHEX(String s) { StringBuffer sb = new StringBuffer(); try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] upshot = digest.digest(s.getBytes()); for (int i = 0; i < outcome.length; i++) { String hex = Integer.toHexString(0xff & issue[i]); if (hex.length() == ane) sb.append('0'); sb.append(hex); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return sb.toString(); } } 62. Challenge : Java Visitor Pattern
Annotation: In this problem youmust Not generate whatsoever output on your ain. Any such solution will exist considered as being against the rules and its author volition be butterfingers. The output of your solution must be generated by the uneditable code provided for you in the solution template.
An important concept in Object-Oriented Programming is the open/closed principle, which means writing code that is open toextension but airtight tomodification. In other words, new functionality should exist added by writing an extension for the existing code rather than modifying it and potentially breaking other code that uses it. This challenge simulates a real-life problem where the open/closed principle tin and should be applied.
ATree class implementing a rooted tree is provided in the editor. It has the following publicly available methods:
-
getValue(): Returns thevalue stored in the node. -
getColor(): Returns thecolour of the node. -
getDepth(): Returns the depth of the node. Recollect that the depth of a node is the number of edges between the node and the tree's root, then the tree's root has depth0 and each descendant node's depth is equal to the depth of its parent node+1 .
In this challenge, we treat the internal implementation of the tree every bit being closed to modification, and so we cannot directly modify it; all the same, as with real-world situations, the implementation is written in such a way that information technology allows external classes to extend and build upon its functionality. More than specifically, information technology allows objects of theTreeVis class (a Visitor Design Blueprint) to visit the tree and traverse the tree structure via theaccept method.
In that location are ii parts to this challenge.
Role I: Implement Three Different Visitors
Each class has 3 methods y'all must write implementations for:
-
getResult(): Return an integer denoting theresult , which is different for each class:- TheSumInLeavesVisitor implementation must return the sum of the values in the tree'sleaves only.
- TheProductRedNodesVisitor implementation must return theproduct of values stored in allcerise nodes, including leaves, computed modulo 10nine + vii. Notation that the product of zero values is equal to 1 .
- TheFancyVisitor implementation must render the absolute difference between the sum of values stored in the tree'southnon-leaf nodes at even depth and the sum of values stored in the tree'sgreen leaf nodes. Recall that nix is an fifty-fifty number.
-
visitNode(TreeNode node): Implement the logic responsible for visiting the tree'southwardnon-leaf nodes such that thegetResultmethod returns the correctoutcome for the implementing class' visitor. -
visitLeaf(TreeLeaf leaf): Implement the logic responsible for visiting the tree'sleaf nodes such that thegetResultmethod returns the right result for the implementing course' company.
Role Two: Read and Build the Tree
Read thedue north -node tree, where each node is numbered fromi ton . The tree is given as a list of node values (), a list of node colors (), and a list of edges. Construct this tree as an instance of theTree grade. The tree is always rooted at node number.
Your implementations of the iii visitor classes volition be tested on the tree you built from the given input.
Input Format
The first line contains a unmarried integer,, denoting the number of nodes in the tree. The second line contains space-separated integers describing the respective values of x 1,x2,…,10n . The third line containsn space-separated binary integers describing the respective values of c i,c2,…,cnorthward . Each c i denotes the color of the ith node, where 0 denotesblood-red and1 denotesgreen.
Each of then – 1 subsequent lines contains two space-separated integers, u i and five i , describing an edge between nodes u i and five i .
Constraints
-
2 ≤ due north ≤ ten5
-
i ≤ xi ≤ ten3
-
ci ∈ {0,ane}
-
ane ≤ vi,ui ≤ n
- It is guaranteed that the tree is rooted at node1 .
Output Format
Do non impress anything to stdout, every bit this is handled by locked stub code in the editor. The iiigetResult() methods provided for y'all must return an integer cogent theupshot for that class' visitor (divers above). Note that the value returned pastProductRedNodesVisitor'sgetResult method must exist computed modulo 109 + 7 .
Sample Input
five 4 7 2 5 12 0 1 0 0 i 1 2 1 iii 3 4 3 v Sample Output
24 40 15
Solution:
enum Colour { RED, Green } abstract class Tree { private int value; individual Colour color; individual int depth; public Tree(int value, Color color, int depth) { this.value = value; this.color = color; this.depth = depth; } public int getValue() { render value; } public Color getColor() { return color; } public int getDepth() { return depth; } public abstract void accept(TreeVis company); } class TreeNode extends Tree { private ArrayList<Tree> children = new ArrayList<>(); public TreeNode(int value, Color color, int depth) { super(value, color, depth); } public void have(TreeVis visitor) { visitor.visitNode(this); for (Tree kid : children) { child.accept(company); } } public void addChild(Tree child) { children.add(child); } } form TreeLeaf extends Tree { public TreeLeaf(int value, Color color, int depth) { super(value, color, depth); } public void accept(TreeVis company) { visitor.visitLeaf(this); } } abstract class TreeVis { public abstract int getResult(); public abstract void visitNode(TreeNode node); public abstract void visitLeaf(TreeLeaf leaf); } class SumInLeavesVisitor extends TreeVis { private int upshot = 0; public int getResult() { return result; } public void visitNode(TreeNode node) { // practise naught } public void visitLeaf(TreeLeaf leaf) { result += leaf.getValue(); } } course ProductOfRedNodesVisitor extends TreeVis { individual long result = one; private terminal int M = 1000000007; public int getResult() { render (int) upshot; } public void visitNode(TreeNode node) { if (node.getColor() == Color.RED) { result = (result * node.getValue()) % M; } } public void visitLeaf(TreeLeaf leaf) { if (leaf.getColor() == Colour.Ruby) { event = (result * leaf.getValue()) % Grand; } } } class FancyVisitor extends TreeVis { private int nonLeafEvenDepthSum = 0; private int greenLeavesSum = 0; public int getResult() { return Math.abs(nonLeafEvenDepthSum - greenLeavesSum); } public void visitNode(TreeNode node) { if (node.getDepth() % 2 == 0) { nonLeafEvenDepthSum += node.getValue(); } } public void visitLeaf(TreeLeaf leaf) { if (leaf.getColor() == Color.GREEN) { greenLeavesSum += leaf.getValue(); } } } public form JavaVisitorPattern { static int[] values; static Color[] colors; static ArrayList<Integer>[] edges; // each edges[i] holds arrayList of all nodes connnected to node i @SuppressWarnings("unchecked") public static Tree solve() { int north; TreeNode root; Scanner sc = new Scanner(Arrangement.in); n = sc.nextInt(); values = new int[n]; colors = new Color[north]; for (int i = 0; i < northward; i++) values[i] = sc.nextInt(); for (int i = 0; i < n; i++) colors[i] = sc.nextInt() == 0 ? Color.Crimson : Color.Light-green; // initialize arraylists edges = (ArrayList<Integer>[]) new ArrayList[north + 1]; for (int i = 1; i <= northward; i++) edges[i] = new ArrayList<Integer>(); // read the n- 1 edges and shop them in both directions for (int i = 0; i < due north - one; i++) { int edgeNode1 = sc.nextInt(); int edgeNode2 = sc.nextInt(); edges[edgeNode1].add together(edgeNode2); edges[edgeNode2].add(edgeNode1); } sc.shut(); root = new TreeNode(values[0], colors[0], 0); // root is ever internal addChildren(root, i); render root; } public static void addChildren(Tree node, Integer nodeNumber) { // for all edges coming out of this node for (Integer otherNodeNumber : edges[nodeNumber]) { Tree otherNode; if (edges[otherNodeNumber].size() > 1) // new internal node otherNode = new TreeNode(values[otherNodeNumber - 1], colors[otherNodeNumber - 1], node.getDepth() + one); else // new leaf otherNode = new TreeLeaf(values[otherNodeNumber - ane], colors[otherNodeNumber - one], node.getDepth() + 1); ((TreeNode) node).addChild(otherNode); edges[otherNodeNumber].remove(nodeNumber); // remove reverse edge if (otherNode instanceof TreeNode) addChildren(otherNode, otherNodeNumber); } } public static void main(String[] args) { Tree root = solve(); SumInLeavesVisitor vis1 = new SumInLeavesVisitor(); ProductOfRedNodesVisitor vis2 = new ProductOfRedNodesVisitor(); FancyVisitor vis3 = new FancyVisitor(); root.have(vis1); root.take(vis2); root.accept(vis3); int res1 = vis1.getResult(); int res2 = vis2.getResult(); int res3 = vis3.getResult(); System.out.println(res1); System.out.println(res2); System.out.println(res3); } } Source: https://www.kodnest.com/java/
0 Response to "How to Read Input From Standard Input Hackerrank Java"
إرسال تعليق