-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReplaceAllEnterString.java
More file actions
53 lines (39 loc) · 1.47 KB
/
ReplaceAllEnterString.java
File metadata and controls
53 lines (39 loc) · 1.47 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
import java.util.Scanner;
/**
* 30.How to replace entered string ReplaceAllEnterString() in java Program.
*/
public class ReplaceAllEnterString {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
String input, wordToReplace, replaceString;
while (true) {
System.out.print("Enter the sentence: ");
input = scan.nextLine().trim();
System.out.print("Enter the word/substring to replace: ");
wordToReplace = scan.nextLine().trim();
System.out.print("Enter the new replacement word: ");
replaceString = scan.nextLine().trim();
if (input.isEmpty() || wordToReplace.isEmpty() || replaceString.isEmpty()) {
System.out.println("Error: Input cannot be empty. Please try again.");
continue;
}
if (!input.matches("[a-zA-Z .,']+") || !wordToReplace.matches("[a-zA-Z .,']+")
|| !replaceString.matches("[a-zA-Z .,']+")) {
System.out.println(
"Error: Input must contain only letters, spaces, '.', ',', or '''. Please try again.");
continue;
}
if (!input.contains(wordToReplace)) {
System.out.println(
"Error: The word '" + wordToReplace + "' is not found in the sentence. Try again.");
continue;
}
break;
}
String updatedSentence = input.replaceAll(wordToReplace, replaceString);
System.out.println("Updated sentence: " + updatedSentence);
} catch (Exception e) {
System.out.println("Unexpected error occurred: " + e.getMessage());
}
}
}