Using Java: Write a program that asks the user to enter a sentence. Using matche
ID: 3723490 • Letter: U
Question
Using Java: Write a program that asks the user to enter a sentence. Using matches method using only one pattern validate that the entered sentence consists only of letters and ends with either: a period, an exclamation mark, or a question mark. To check if the given string represents a valid sentence define a pattern.
If it is not a valid sentence, your program should output that the input is not valid.
Otherwise the input should be displayed with all the vowels replaced with an #character
The following shows sample runs of the program:
Run #2
Run #4
Explanation / Answer
ReplaceVowelsWithHash.java
import java.util.Scanner;
public class ReplaceVowelsWithHash {
public static void main(String[] args) {
//Declaring variables
String str;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
str=sc.nextLine();
//calling the method
boolean bool=CheckValid(str);
if(!bool)
{
System.out.print("The entered input ""+str+"" is not a valid.");
}
else
{
//calling the method
String newStr=replaceVowels(str);
System.out.println(newStr);
}
}
//This method will replace the vowels with #
private static String replaceVowels(String str) {
String newStr="";
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='a' ||str.charAt(i)=='e'|| str.charAt(i)=='i'||str.charAt(i)=='o'||str.charAt(i)=='u'||
str.charAt(i)=='A'||str.charAt(i)=='E'||str.charAt(i)=='I'||str.charAt(i)=='O'||str.charAt(i)=='U')
newStr+="#";
else
newStr+=str.charAt(i);
}
return newStr;
}
//This method will validate the user inout is valid or not
private static boolean CheckValid(String str) {
for(int i=0;i<str.length();i++)
{
if((str.charAt(i)<65 || str.charAt(i)>90) && (str.charAt(i)<97 || str.charAt(i)>122) && (str.charAt(i)!='.' && str.charAt(i)!='?' && str.charAt(i)!='!' && str.charAt(i)!=' '))
{
return false;
}
}
return true;
}
}
_________________
Output#1
The first sentence is not valid
The entered input "The first sentence is not valid" is not a valid.
____________
Output#2:
The 2nd sentence is also invalid!
The entered input "The 2nd sentence is also invalid!" is not a valid.
____________
Output#3:
A very NICE sentence.
# v#ry N#C# s#nt#nc#.
_____________
Output#4:
Do you like programming?
D# y## l#k# pr#gr#mm#ng?
_____________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.