-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIndexOfInput.java
More file actions
46 lines (35 loc) · 1.24 KB
/
IndexOfInput.java
File metadata and controls
46 lines (35 loc) · 1.24 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
import java.util.Scanner;
/**
* 29. How to use indesOf() in java Program.
*/
public class IndexOfInput {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
String input, searchString;
while (true) {
System.out.print("Enter the sentence: ");
input = scan.nextLine().trim();
System.out.print("Enter the word/substring to find its index: ");
searchString = scan.nextLine().trim();
if (input.isEmpty() || searchString.isEmpty()) {
System.out.println("Error: Input cannot be empty. Please try again.");
continue;
}
if (!input.matches("[a-zA-Z .,']+") || !searchString.matches("[a-zA-Z .,']+")) {
System.out.println("Error: Input must contain only letters and spaces. Please try again.");
continue;
}
break;
}
// Find the index of the search string in the input sentence
int index = input.indexOf(searchString);
if (index != -1) {
System.out.println("The substring '" + searchString + "' starts at index: " + index);
} else {
System.out.println("The substring '" + searchString + "' was not found in the given sentence.");
}
} catch (Exception e) {
System.out.println("Unexpected error occurred: " + e.getMessage());
}
}
}