-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp05.java
More file actions
60 lines (53 loc) · 1.85 KB
/
App05.java
File metadata and controls
60 lines (53 loc) · 1.85 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.Scanner;
public class App05 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// Compile time Polymorphism (Preferably replace "App05" with "Polymorphism" everywhere, even file name)
App05 obj1 = new App05();
System.out.print("Enter first string: ");
String s1 = scan.nextLine();
System.out.print("Enter second string: ");
String s2 = scan.nextLine();
obj1.compare(s1, s2);
System.out.print("Enter number of characters to compare: ");
int n = scan.nextInt();
obj1.compare(s1, s2, n);
scan.close();
}
public void compare(String s1, String s2) {
if (s1.compareTo(s2) == 0) {
System.out.println("The 2 strings are same");
} else {
System.out.println("The 2 strings are not same");
}
}
public void compare(String s1, String s2, int n) {
int flag = 0;
for (int i = 0; i < n; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
flag = 1;
}
}
if (flag == 0) {
System.out.println("The 2 strings are same upto " + n + " characters");
} else {
System.out.println("The 2 strings are not same upto " + n + " characters");
}
}
}
// Output:
// Enter first string: hello
// Enter second string: world
// The 2 strings are not same
// Enter number of characters to compare: 1
// The 2 strings are not same upto 1 characters
// Enter first string: hello
// Enter second string: hello
// The 2 strings are same
// Enter number of characters to compare: 3
// The 2 strings are same upto 3 characters
// Enter first string: helloworld
// Enter second string: hellcat
// The 2 strings are not same
// Enter number of characters to compare: 4
// The 2 strings are same upto 4 characters