March 16, 2022

HackerRank Java

You must print two lines of output

​ Print Hello, World. on the first line.
​ Print Hello, Java. on the second line.

Sample Output

​ Hello, World.
​ Hello, Java.


Just simple Ctrl + C from the question part & Ctrl + V to the code block. Done.

1
2
3
4
5
6
7
8
9
10
public class Solution 
{

public static void main(String[] args)
{
/* Enter your code here. Print output to STDOUT. Your class should be named Solution. */
System.out.println("Hello, World.");
System.out.println("Hello, Java.");
}
}

3 types of print statements


A print statement is a call to the print / println method of the System.out object.

The print method takes exactly one argument;

The println method takes one or no arguments.


The arguments maybe a String which you create using the string concatenation “+” or an object, the print and println methods call that object’s toString() method to get a printable string.


Stdin and Stdout I

​ Two ways –> Scanner class OR BufferedReader class

Scanner: specifying Input Stream as System.in.

1
2
3
4
5
6
7
8
9
10
11
12
// create a Scanner Object named scan
Scanner scan = new Scanner(System.in);

// use Scanner scan to read a String and an int
String myString = scan.next();
int myInt = scan.nextInt();

// close Scanner Object because no more input to read
scan.close();

System.out.println("myString is: " + myString);
System.out.println("myInt is: " + myInt);

BufferedReader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
FileReader fr = new FileReader("File.txt");
// or use InputStreamReader
// InputStreamReader insreader =new InputStreamReader(System.in);

// create a BufferedReader Object
BufferedReader bfreader = new BufferedReader(fr);

String name="";
while(!name.equals("stop"))
{
System.out.println("Enter data: ");
name = bfreader.readLine();
System.out.println("data is: "+ name);
}

bfreader.close();
fr.close();

bfreader.close();

Read integers from stdin and then print them to stdout. Each integer must be printed on a new line.

Sample Input

42

100

125

Sample Output

42

100

125

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.*;

public class Solution {

public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
// Complete this line
// Complete this line

System.out.println(a);
System.out.println(b);
System.out.println(c);
// Complete this line
// Complete this line



// BETTER IDEA
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt())
{
int a = sc.nextInt();
System.out.println(a);
}

// IDEA 2
/*
a Try with Resource to automatically close any classes that
implements AutoClosable interface (Scanner class in this case).
That way you don't have to do scanner.close()
*/
try(Scanner scan = new Scanner(System.in))
{
while (scan.hasNext())
{
System.out.println(scan.nextInt());
}
}
}
}

获取数据类型的取值范围

1
2
3
4
if(a >= Short.MIN_VALUE && a <= Short.MAX_VALUE)
{
System.out.println(“It’s a short type”);
}

int to String

1
2
int n = 3;
String s = String.valueOf(n);

Static Initializer Block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution
{
static Scanner scan = new Scanner(System.in);
static int breadth = scan.nextInt();
static int height = scan.nextInt();

public static void main(String[] args)
{

}

static
{
if(breadth > 0 && height > 0)
{
System.out.println(breadth*height);
}
else
{
System.out.println(“java.lang.Exception: Breadth and height must be positive”);
}
}
}


Get day of the week based on a specific date

Input: 08 05 2015

1
2
3
4
5
6
7
import java.time.LocalDate;

public static String findDay(int month, int day, int year)
{
LocalDate local = LocalDate.of(year, month, day);
return local.getDayOfWeek().toString();
}

Output: WEDNESDAY


Read in content by parts(separate by space)

Input: 08 05 2015

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

int month = Integer.parseInt(firstMultipleInput[0]);

int day = Integer.parseInt(firstMultipleInput[1]);

int year = Integer.parseInt(firstMultipleInput[2]);

String res = Result.findDay(month, day, year);

bufferedWriter.write(res);
bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();
}
}

Currency Format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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) {
Scanner scanner = new Scanner(System.in);
double payment = scanner.nextDouble();
scanner.close();


NumberFormat f1 = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat f2 = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
NumberFormat f3 = NumberFormat.getCurrencyInstance(Locale.CHINA);
NumberFormat f4 = NumberFormat.getCurrencyInstance(Locale.FRANCE);

String us = f1.format(payment);
String india = f2.format(payment);
String china = f3.format(payment);
String france = f4.format(payment);


System.out.println("US: " + us);
System.out.println("India: " + india);
System.out.println("China: " + china);
System.out.println("France: " + france);
}
}

String manipulation

Input:
hello
java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);
String A=sc.next();
String B=sc.next();
/* Enter your code here. Print output to STDOUT. */
// Task 1
System.out.println(A.length()+B.length());

// Task 2
// Compare first letter which is in front
if(A.charAt(0) > B.charAt(0))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}

// Task 3
// Replace first character with upper case
System.out.println(
A.replace(A.charAt(0), Character.toUpperCase(A.charAt(0)))
+ " "
+ B.replace(B.charAt(0), Character.toUpperCase(B.charAt(0))));
}
}

Output:
9
No
Hello Java

Substring

Syntax: substring(startInx, endInx)

1
2
String s = “HelloWorld”;
System.out.println(s.substring(1,4));

Output:
ello


char to String

1
2
char c = ‘M’;
String s = Character.toString(c);

Convert String array to char array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class CharArrayDemo4 
{
public static void main(String[] args)
{
String value = "JavaTPoint";

//Convert string to a char array.
char[] array = value.toCharArray();

for(char c : array)
{
System.out.println(c);
}
}
}

Java Palindrome(String reverse)

Palindrome explanation:
If a word/sentence read the same either from the front to end or end to front, then it is a palindrome word/sentence.

Eg. madam is a palindrome word.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.*;
import java.util.*;

public class Solution
{

public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String A = sc.next();

int capacity = A.length();
char[] list1 = new char[capacity];
char[] list2 = new char[capacity];

for(int i = 0; i < A.length(); i++)
{
list1[i] = A.charAt(i);
}

int index = 0;
for(int j = capacity-1; j >= 0; j--)
{
list2[index] = A.charAt(j);
index++;
}

if(Arrays.equals(list1, list2))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}

Better Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.; 
import java.util.;

public class Solution
{
public static void main(String[] args)
{

String rev = " ";
Scanner sc = new Scanner(System.in);
String A = sc.next();

for (int i = A.length()-1; i >= 0; i--)
{
rev += A.charAt(i);
}

if (A.equals(rev.trim()))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}

注:这里没必要加.trim(), 把rev定义为””就好。
trim()的目的是去掉一段String的开头和结尾处的空白。


replaceAll Regex Example

regex内特殊字符用[]包括即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
// Write your code here.

String[] parts = s.replaceAll("[ !._@,'?]"," ").split(" ");

int num = 0;
for(String sss : parts)
{
if(sss.length() != 0)
{
num++;
}
}
System.out.println(num);

for(String ss : parts)
{
if(ss.length() == 0)
{
continue;
}
else
{
System.out.println(ss);
}

}
scan.close();
}
}

Pattern compile

Compile the given regular expression into a pattern.

1
2
3
public static Pattern compile(String regex)

// Throws PatternSyntaxException if the expression syntax is invalid.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.util.Scanner;
import java.util.regex.*;

public class Solution
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int testcase = Integer.parseInt(in.nextLine());

while(testcase > 0)
{
String pattern = in.nextLine();

try
{
Pattern check = Pattern.compile(pattern);
System.out.println(“Valid”);
}
catch(PatternSyntaxException e)
{
System.out.println(“Invalid”);
}
testcase—-;
}
}
}


Reference

About this Post

This post is written by Andy, licensed under CC BY-NC 4.0.

#Java#HackerRank