-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCompareString.java
More file actions
36 lines (31 loc) · 1.26 KB
/
CompareString.java
File metadata and controls
36 lines (31 loc) · 1.26 KB
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
import java.util.Scanner;
/**
* 13. How to complete 2 string in Java program.
*/
public class CompareString {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the First String:");
String str1 = scan.nextLine().trim();
System.out.println("Enter the Second String:");
String str2 = scan.nextLine().trim();
// Validate inputs (allows alphabets and spaces)
if((!str1.equals(null))&&str1.matches("^[a-zA-Z\\s]+$") &&
(!str2.equals(null))&&str2.matches("^[a-zA-Z\\s]+$")) {
//Compare String
int comparisonResult = str1.compareToIgnoreCase(str2);
if (comparisonResult > 0) {
System.out.println("First string is greater than second.");
}else if (comparisonResult < 0) {
System.out.println("First string is smaller than second.");
}else {
System.out.println("Both String are Equals.");
}
}else {
System.out.println("Invalid input! Please enter strings containing only alphabets and spaces.");
}
} catch (Exception e) {
System.out.println("An unexpected error occurred. Please try again.");
}
}
}