Display only one kind of the vowel - java

I need to display only one type of the vowel that have check from a string
but it keeps on display the repeated vowel.
Input: I am in you all day and wathc you over.
Output:
Vowels : I a o u e
Consonants : m n y l d w t h c r
this means it will display the vowel that was used in the sentence.
the same goes for the consonant
import java.util.Scanner;
public class aaaa {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
System.out.println ("Enter a string:");
String s = input.nextLine();
char[] sChars = s.toCharArray();
char[] vowels = {'a','e','i','o','u','A','E','I','O','U'};
char[] consonant = {'b','c','d','f','g','h','k','j','l','m','n','p','q','r','s','t','x','v','w','y','z'};
for (int j = 0 ; j < sChars.length ; j++ ) {
for (int i = 0; i < vowels.length ; i++ ) {
if ( sChars[j] == vowels[i]) {
System.out.print(vowels[i]+ " ");
}
}
}
System.out.print("\n");
for(int m = 0 ; m < sChars.length ; m++){
for(int n = 0; n < consonant.length ; n++){
if ( sChars[m] == consonant[n]){
System.out.print(consonant[n]+" ");
}
}
}
}
}

Try this:
System.out.println("Vowels: " + s.toLowerCase().replaceAll("[^aeiou]|(.)(?=.*\\1)", "")
+ "\nConsonants: " + s.toLowerCase().replaceAll("[aeiou]|(.)(?=.*\\1)", ""));
This gets the entire job done in one line by using regex to select the characters of interest to delete.
FYI, the regex [aeiou]|(.)(?=.*\1) means "any vowel, or any character that does not reappear". The first match of an alternation stops there, that's why I didn't need to code the character class for consonants in the right hand side - the dot will only match for non-vowels.
A similar approach is used for printing vowels, except it's a negated character class.

There are way more efficient ways of doing this, but I will try to change as little of your solution as possible.
Keep track of the letters already printed, and don't print them a second time:
char[] vowels = {'A','E','I','O','U'};
char[] consonant = {'B','C','D','F','G','H','K','J','L','M','N','P','Q','R','S','T','X','V','W','Y','Z'};
// create a collection to store the letters already used
List<Character> lettersUsed = new ArrayList<Character>();
for (int j = 0 ; j < sChars.length ; j++ ) {
for (int i = 0; i < vowels.length ; i++ ) {
if ( Character.toUpperCase(sChars[j]) == vowels[i]) {
// if the collection of used letters does not contain this one
if(!lettersUsed.contains(Character.toUpperCase(sChars[j]))) {
System.out.print(sChars[j]+ " ");
// add this letter to the collection of letters used
lettersUsed.add(Character.toUpperCase(sChars[j]));
}
// now that you've found a match, break out of the inner loop
break;
}
}
}
System.out.print("\n");
for(int m = 0 ; m < sChars.length ; m++){
for(int n = 0; n < consonant.length ; n++){
if ( Character.toUpperCase(sChars[m]) == consonant[n]){
// if the collection of used letters does not contain this one
if(!lettersUsed.contains(Character.toUpperCase(sChars[m]))) {
System.out.print(sChars[m]+" ");
// add this letter to the collection of letters used
lettersUsed.add(Character.toUpperCase(sChars[m]));
}
// now that you've found a match, break out of the inner loop
break;
}
}
}

Related

How do I exit out from an if-statement in a for loop?

I want the program to run the if statement for the first iteration of the for loop, and then ignore it for the rest of the iterations. How do I do that? Continue and break didn't work either and led to a wacky output. The program is meant to take the first letter of each word in a string inputted and then form a word with those letters.
import java.util.Scanner;
class First_letter
{
public static void main()
{
System.out.println("\f"); // clearing screen
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = sc.nextLine();
String S = s.toUpperCase();
String NS = "";
char c = Character.MIN_VALUE;
for (int i = 0; i < S.length(); i++)
{
if( i == 0 && Character.isLetter(S.charAt(0)))
{
NS = NS + S.charAt(0);
}
if (S.charAt(i) == ' ')
{
if (Character.isLetter(S.charAt(i+1)) == true)
{
c = S.charAt(i);
NS = NS + c;
}
}
}
System.out.println("The word formed from the first letter of all the words in the sentence is "+NS);
}
}
Assuming I understand your intent:
If you only want code to execute for the first loop iteration, there's no reason for that code to be in the loop.
if (S.length() != 0 && Character.isLetter(S.charAt(0)))
{
NS = NS + S.charAt(0);
}
for (int i = 0; i < S.length(); i++)
{
if (S.charAt(i) == ' ')
{
if (Character.isLetter(S.charAt(i+1)) == true)
{
c = S.charAt(i);
NS = NS + c;
}
}
}
Note length check before accessing the 0'the character.
For clarity, the two 'ifs' inside the loop can be combined into one, using the '&&' logical operator, but I left that part unchanged.
If I understand your questions correctly, you want to create a WORD from the first letter of every word in the sentence.
If this is true then the following should solve it. Let's keep it simple.
Split the sentences into words.
Take the first char from every word.
Change it to upper case.
And finally, join the result of every word.
public static void main(String[] args) {
System.out.println("\f"); // clearing screen
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence: ");
System.out.println("The word formed from the first letter of all the words in the sentence is "
+ Joiner.on("")
.join(Arrays.stream(sc.nextLine().split("\\s+"))
.filter(StringUtils::isNotBlank)
.map(w -> w.charAt(0))
.map(Character::toUpperCase).toList()
)
);
}

ArrayIndexOutOfBoundsException when finding words in an array that and with a specific letter

I am trying to find words in an array that end with a letter 'a'. I thought of doing it using two for loops but I keep getting integer out of bounds error.
Could anyone tell me what i am doing wrong?
The code:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
for (int i = 0; i < words.length; i++) {
words[i] = words[i] + " ";
}
for (int i = 0; i < words.length ; i++) {
for (int j = 0; j <= words[i].charAt(j); j++) {
if (words[i].charAt(j) == 'a' && words[i].charAt(j + 1) == ' ') {
System.out.println(words[i]);
}
}
}
You've got too much code for the task, which has lead to a bug creeping in and hiding in plain sight. As a general rule, keeping code as simple as possible results in less bugs.
Delete this, which you don't need.
for (int i = 0; i < words.length; i++) {
words[i] = words[i] + " ";
}
And delete all of this:
for (int j = 0; j <= words[i].charAt(j); j++) {
if( words[i].charAt(j) == 'a' && words[i].charAt(j + 1) == ' '){
System.out.println(words[i]);
}
}
instead basing your code on endsWith("a"):
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
which is easy to read and understand (and thus easier to avoid bugs).
Even simpler, since you don't need to reference the array, use the result of the split directly:
String text = sc.nextLine();
for (String word : text.split(" ")) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
In your second for loop, you are checking against the character at the current position, not the length of the word. Change the condition to words[i].length()to fix it.
In order to check if some words end with character a, we can do the following:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read the input
System.out.println("Enter text: ");
String text = sc.nextLine();
// Split the input by spaces
String[] words = text.split(" ");
// Iterate through the array of words and check if any of those ends with "a"
for (String word : words) {
if (word.endsWith("a")) {
System.out.println(word);
}
}
}
It would be simple as that, we don't really need an embedded loop.
Try this instead
String[] words = {"apple", "ada", "cat", "material", "recursion", "stacksa"};
for (int i = 0; i < words.length; i++) {
// get each word first
String word = words[I];
int lenOfWord = word.length();
// check the last item in the word
if (word.charAt(lenOfWord - 1) == 'a') {
System.out.println("Last char is a" + word);
}
}
Other answers explain the logic via loops. Another approach to do the same could be through Java streams:
Scanner sc = new Scanner(System.in);
System.out.println("Enter text: ");
String text = sc.nextLine();
String[] words = text.split(" ");
Arrays.stream(words).filter(w -> w.endsWith("a")).forEach(System.out::println);

Read in a sentence and print out only words that have the same letter repeated 3 or more times in a row

I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers

How to print a distinct string in this pattern in Java?

I am trying to make a program in java which would give a pattern for an inputted string as follows
C O M P U T E R
O E
M T
P U
U P
T M
E O
R E T U P M O C
Here is my program code
import java.util.Scanner;
class pandapattern
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a word : ");
String s=sc.nextLine();
System.out.println();
int l=s.length();
for(int i=0;i<+l;i++)
{
System.out.print(s.charAt(i)+" ");
}
char[][] frwd = new char[l][1];
char[][] bcwd = new char[l][1];
for(int f=1;f<l;f++)
{
frwd[f][0]=s.charAt(f);
}
for(int b=l-2;b>=0;b--)
{
bcwd[b][0]=s.charAt(b);
}
for(int p=1;p<l;p++)
{
System.out.print("\n"+frwd[p][0]);
}
for(int p1=l-1;p1>=0;p1--)
{
System.out.print(bcwd[p1][0]+" ");
}
}
}
I get this pattern:
C O M P U T E R
O
M
P
U
T
E
R E T U P M O C
How would I get the whole pattern printed out?
Please help me to figure it out.
You onle need one char[] array, not more.
The trick is to take the problem "row-by-row".
See below:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter word for Panda Pattern: ");
String word = scanner.nextLine();
String wspace = " ";
//convert user input from String to char[]
char[] wordLetters = word.toCharArray();
//define array's length, for ease of reference
int length = wordLetters.length;
//initially print the sentence in a horizontal line
for (char wordLetter : wordLetters) {
System.out.print(wordLetter + wspace);
}
//insert new line to start printing for the pattern
System.out.print("\n");
/*A for loop that will print the left-most letters vertically
We start the loop from 1, because the first letter was already printed*/
for(int i=1; i<length; i++){
System.out.print(wordLetters[i]);
/*now we have an inner loop that will print the spaces and the
rest of the letters in reverse order*/
for(int j=1; j<length; j++){
//conditional for IF we are at final line
if(i == length-1 && j != length-1)
System.out.print(wspace + wordLetters[i-j]);
//conditional for printing right-most letters
else if(j == length-1) {
System.out.print(wspace + wordLetters[j-i]+"\n");
}
//THIS WILL PRINT 2 WHITE-SPACES.
else
System.out.print(wspace + wspace);
}
}
}
Why didn't I need a second array ?
Since this pattern requires only one word, then printing in reverse, means that there is still the same amount of letters to process, so any additional arrays would have the same length.
Ergo, we can omit creating new arrays altogether!
Why not manipulate the power that for-loops & arrays give us?
Firstly, for this task you need one-dimension arrays frwd and bcwr
Secondly, you fill array bcwd in the same way as frwd.
Rewritten part of your method correctly for the task:
int length = s.length();
//printing first line
for (int i = 0; i < +length; i++) {
System.out.print(s.charAt(i) + " ");
}
System.out.println();
//filling arrays
char[] frwd = new char[length];
char[] bcwd = new char[length];
for (int f = 1; f < length; f++) {
frwd[f] = s.charAt(f);
}
for (int b = 0; b < length; b++) {
bcwd[b] = s.charAt(length-1 - b);
}
for (int p = 1; p < length-1; p++) {
System.out.print(frwd[p]);
//filling spaces to line by length of input string
for (int p3 = 1; p3 < frwd.length-1; p3++) {
System.out.print(" " + " ");
}
System.out.print(" " + bcwd[p]);
System.out.println();
}
for (int p = 0; p <= length - 1; p++) {
System.out.print(bcwd[p] + " ");
}
System.out.println();
And you can use just input string without extra char arrays. Just get characters from string (s.charAt(i)) in straight and backwar loops.

Counting Upper and Lower characters in a string using an array

I have been working on this problem for two days now and have no idea where I'm going wrong.
Essentially I need to ask a user for a string of words.
I need to set up an int array of 26 elements that holds the count of lower case letters and one for upper case letters.
I can't get the program to compare with the array elements properly. This is my code so far:
public class Lab17Array {
public static void main(String[] args)
{
Scanner kb = new Scanner (System.in);
int lLetter = 0;
int uLetter = 0;
// int[] alph = new int [26];
int alph [] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int Alph [] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
System.out.println("Enter a phrase");
String user = kb.nextLine();
// to print out length of word
System.out.println("Total number of letters is " + user.length());
for(int i = 0; i < user.length(); i++)
{
}
System.out.println("Upper case letters are:" + uLetter);
System.out.println("Lower case letters are:" + lLetter);
int otherL = user.length() - (uLetter + lLetter);
// to print out other chars that aren't letters
System.out.println("Number of all other letters is " + otherL );
}
}
Inside my for loop is where I've been trying different if conditions. I have no idea what I'm missing?
Using an Array
You could use String.toCharArray() and a for-each loop to iterate your userInput (you seem to have changed the variable name between your post, and your comment). Regardless, something like
for (char ch : user.toCharArray()) {
if (Character.isLowerCase(ch)) {
lLetter++;
} else if (Character.isUpperCase(ch)) {
uLetter++;
}
}
Using Regular Expression(s)
You could reduce your code by using a regular expression to remove all non-lowercase characters from the input and another to remove all non-uppercase characters from the input like
int lLetter = user.replaceAll("[^a-z]", "").length(); // <-- removes everything not a-z
int uLetter = user.replaceAll("[^A-Z]", "").length(); // <-- removes everything not A-Z
Try this
int upperCount = 0;
int lowerCount = 0;
Scanner sc = new Scanner(System.in);
String w = sc.nextLine();
for(int i = 0; i < w.length(); i++){
if(Character.isUpperCase(w.charAt(i))){
upperCount++;
}else{
lowerCount++;
}
}
System.out.println("Upper Counts are "+upperCount+" lower counts are "+lowerCount);
Try this.
for(int i = 0; i < user.length(); i++)
{
int ch = user.charAt(i);
if (Arrays.binarySearch(alph, ch) >= 0)
++lLetter;
if (Arrays.binarySearch(Alph, ch) >= 0)
++uLetter;
}

Categories

Resources