Find the number of substring of a string that satisfy a criteria - java

Question:
Given a string a, find the number of subsegments of the string that contain at least one vowel AND one consonant. For example : input "blue" will have number of subsgments = 1, "hackerrank" will return number of segments = 3 ("ha","cker","rank") each will contain at least one consonant and one vowel.
Here is my code in Java
public static int segments(String password){
int numbersegments = 0;
int vowel = 0;
int consonant = 0;
for(int index = 0; index < password.length();index++){
if(password.charAt(index) == 'a' || password.charAt(index) == 'e' ||
password.charAt(index) == 'i' || password.charAt(index) == 'u'
|| password.charAt(index) == 'o' ){
vowel++;
}
else
consonant++;
if(vowel >= 1 && consonant >= 1){
numbersegments++;
vowel = 0;
consonant = 0;
}
}
return numbersegments;
}
I run the test cases with code above and it shows 5 out of 15 ouputs are correct. Unfortunately i can't see the input for those incorrect testcases so there is no way i can see the missing logic for my code above to run 100% correct on all cases. Maybe i didn't take into account certain edge cases but i cannot think of any. Is there any flaw of my code above ? Is there any missing cases that i forget to take into account ? Thank you

Try this, I think it will work
public static int segments(String password){
int numbersegments = 0;
int vowel = 0;
int consonant = 0;
password = password.toLowerCase();
for(int index = 0; index < password.length();index++){
if(password.charAt(index) == 'a' || password.charAt(index) == 'e' ||
password.charAt(index) == 'i' || password.charAt(index) == 'u'
|| password.charAt(index) == 'o' ){
vowel++;
}
else if(password.charAt(index)>='a' && password.charAt(index)<='z')
consonant++;
if(vowel >= 1 && consonant >= 1){
numbersegments++;
vowel = 0;
consonant = 0;
}
}
return numbersegments;
}
You did not take into consideration CAPs, special characters & numbers. you check small letter vowels only.

Related

Vowel substring

I have to write a program that takes a String as user input and then prints a substring that starts with the first vowel of the String and ends with the last. So for instance if my String is : "Hi I have a dog named Patch", the printed substring would be : "i I have a dog named Pa"
This is the code I have now:
import java.util.Scanner;
import java.util.*;
public class SousChaineVoyelle {
private static Scanner sc;
public static void main (String[] args) {
sc = new Scanner(System.in);
System.out.print("Enter a String: ");
String str = sc.nextLine();
int pos1 = 0;
int pos2 = 0;
int i;
int j;
boolean isVowel1 = false;
boolean isVowel2 = false;
for (i = 0; i < str.length(); i++){
if (str.charAt(i) == 'A' || str.charAt(i) == 'a' ||
chaine.charAt(i) == 'E' || str.charAt(i) == 'e' ||
str.charAt(i) == 'I' || str.charAt(i) == 'i' ||
str.charAt(i) == 'O' || str.charAt(i) == 'o' ||
str.charAt(i) == 'U' || str.charAt(i) == 'u' ||
str.charAt(i) == 'Y' || str.charAt(i) == 'y'){
isVowel1 = true;
break;
}
}
if (isVowel1){
pos1 = str.charAt(i);
}
for (j = str.length() - 1; j > i; j--){
if (str.charAt(j) == 'A' || str.charAt(j) == 'a' ||
str.charAt(j) == 'E' || str.charAt(j) == 'e' ||
str.charAt(j) == 'I' || str.charAt(j) == 'i' ||
str.charAt(j) == 'O' || str.charAt(j) == 'o' ||
str.charAt(j) == 'U' || str.charAt(j) == 'u' ||
str.charAt(j) == 'Y' || str.charAt(j) == 'y'){
isVowel2 = true;
break;
}
}
if (isVowel2){
pos2 = str.charAt(j);
}
String sub = chaine.substring(pos1, pos2);
System.out.print(The substring from the first vowel to the last is "\"" + sub +"\"");
}
}
this got me this:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)
at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)
at java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
at java.base/java.lang.String.checkIndex(String.java:4557)
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:46)
at java.base/java.lang.String.charAt(String.java:1515)
at SousChaineVoyelle.main(SousChaineVoyelle.java:33)
One way of looking at it is you have a lot of code to do a simple thing, which means more chances for bugs and errors.
Here's a "less code" solution:
str = str.replaceAll("(?i)^[^aeiou]*|[^aeiou]*$", "");
See live demo.
This works by matching all leading and trailing non-vowels (if any) and replacing them with nothing, effectively deleting them.
(?i) makes the match case insensitive.
After the first for loop, i will be str.length() no matter what. You may want to create another variable to hold I when it's found to remedy this.

Creating a string from loop results in java

I need to be able to save the loop results to a string to be able to manipulate the user output. No arrays
I've attempted to convert to string inside the loop which does not make much sense. I can't figure another way to save the results unless I make another method. I am not allowed create arrays.
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter phone number: ");
String number = input.nextLine();
String phone ="";
for (int i = 0; i < number.length(); i++){
if (Character.isLetter(number.charAt(i)))
phone = getNumber(Character.toUpperCase(number.charAt(i)));
else
number.charAt(i);
}
System.out.println("Your number is " + phone);
}
public static int getNumber(char uppercaseLetter){
if (uppercaseLetter >= 'W' && uppercaseLetter <= 'Z')
return 9;
else if (uppercaseLetter >= 'T' && uppercaseLetter < 'W')
return 8;
else if (uppercaseLetter >= 'P' && uppercaseLetter < 'T')
return 7;
else if (uppercaseLetter >= 'M' && uppercaseLetter < 'P')
return 6;
else if (uppercaseLetter >= 'J' && uppercaseLetter < 'M')
return 5;
else if (uppercaseLetter >= 'G' && uppercaseLetter < 'J')
return 4;
else if (uppercaseLetter >= 'D' && uppercaseLetter < 'G')
return 3;
else
return 2;
}
}
should look like: ie. 352-hey-call =
"Your number is 352-439-2255"
Actually, for each char you're looking for the corresponding letter or number, but you don't use it, you need to append them together. Using += operator on String, but as it's in a loop for better performance it's recommended to use a StringBuilder
StringBuilder phone = new StringBuilder();
for (int i = 0; i < number.length(); i++){
if (Character.isLetter(number.charAt(i))){
phone.append(getNumber(Character.toUpperCase(number.charAt(i))));
}else{
phone.append(number.charAt(i));
}
}
System.out.println("Your number is " + phone.toString());

Java word counting [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to count words by using whitespace as my indicator for when there is a new word.
My current code is returning crazy results for wordCounter, but my vowelCounter is working perfectly.
I apologize if this is a basic or simple question...I'm just starting out with Java and I would really appreciate any assistance!
System.out.println("Please enter some text: ");
String fileContent = input.nextLine().toLowerCase();
int vowelCounter = 0;
int wordCounter = 0;
for (int i = 0; i < fileContent.length(); i++) {
if(fileContent.charAt(i) == 'a' || fileContent.charAt(i) == 'e' || fileContent.charAt(i) == 'i'|| fileContent.charAt(i) == 'o' || fileContent.charAt(i) == 'u')
vowelCounter++;
for (int j = 0; j < fileContent.length(); j++) {
if (Character.isWhitespace(fileContent.charAt(j))) {
wordCounter++;
}
}
}
System.out.println("\nVowel Counter: " + vowelCounter);
System.out.println("Word Counter: " + wordCounter);
That is what happens when you have bad indentation. You are having nested for-loops instead of 2 separate for-loops.
Separate your loops like:
for (int i = 0; i < fileContent.length(); i++) {
if(fileContent.charAt(i) == 'a' || fileContent.charAt(i) == 'e' || fileContent.charAt(i) == 'i'|| fileContent.charAt(i) == 'o' || fileContent.charAt(i) == 'u')
vowelCounter++;
}
for (int j = 0; j < fileContent.length(); j++) {
if (Character.isWhitespace(fileContent.charAt(j)))
wordCounter++;
}
Or have them in 1 single for-loop:
for (int i = 0; i < fileContent.length(); i++) {
if(fileContent.charAt(i) == 'a' || fileContent.charAt(i) == 'e' || fileContent.charAt(i) == 'i'|| fileContent.charAt(i) == 'o' || fileContent.charAt(i) == 'u')
vowelCounter++;
else if (Character.isWhitespace(fileContent.charAt(i))) {
wordCounter++;
}
}
Above all, to check that specific characters (such as vowels) exist in your string, you can do it as:
char ch = fileContent.charAt(i);
if("aeiou".contains("" + ch))
You have a redundant loop inside your loop. Just add the second if to the same loop:
for (int i = 0; i < fileContent.length(); i++) {
if(fileContent.charAt(i) == 'a' || fileContent.charAt(i) == 'e' || fileContent.charAt(i) == 'i'|| fileContent.charAt(i) == 'o' || fileContent.charAt(i) == 'u')
vowelCounter++;
else if (Character.isWhitespace(fileContent.charAt(i)))
wordCounter++;
}
You might wanna add 1 to the wordcount because it ia counting the number of whitespaces. For eg: in "apple banana", there is 1 whitespace but 2 words. Besides that, counting whitespaces has shortcomings, for instance, when there are two or more consecutive whitespaces between the words.

Java Substring Out of Bounds Error: Solution?

This lab for my intro class requires us to return any user input in pig latin.
The error I seem to keep getting when I run it and type any string into the console is this:
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
The error is found here:
thisWord = x.substring(indexOfCurrentNonLetter +1, indexOfNextNonLetter);
I understand from another post this is the problem:
IndexOutOfBoundsException -- if the beginIndex is negative, or endIndex is >larger than the length of this String object, or beginIndex is larger than >endIndex.
Actually, your right edge of your substring function may be lower than the left >one. For example, when i=(size-1) and j=size, you are going to compute >substring(size-1, 1). This is the cause of you error. (Answer By Bes0ul)
My question is, what is the solution to this problem?
Here are the methods I am using:
public String pigLatin(String x)
{
String thisWord = "";
x += " ";
int indexOfNextNonLetter = 0, indexOfCurrentNonLetter = 0;
for(int i = 0; i < x.length(); i++)
{
System.out.println("At least the loop works"); //Let's play a game called find the issue
if(x.charAt(i) < 65 || x.charAt(i) > 90 && x.charAt(i) < 97 || x.charAt(i) > 122) //if it isn't a letter
{
phrase += x.charAt(i); // add our non character to the new string
for(int j = 0; j < x.substring(i).length(); j++) // find the next character that isn't a letter
{
if(x.charAt(i) < 65 || x.charAt(i) > 90 && x.charAt(i) < 97 || x.charAt(i) > 122)
{
indexOfNextNonLetter = j + i;
if(j+i > x.length())
System.out.print("Problem Here");
indexOfCurrentNonLetter = i;
System.out.println("noncharacter detected"); //I hope you found the issue
j = x.length();
thisWord = x.substring(indexOfCurrentNonLetter +1, indexOfNextNonLetter);//between every pair of nonletters exists a word
}
}
phrase += latinWord(thisWord); // translate the word
i = indexOfNextNonLetter - 1;
}
}
return phrase;
}
/*
* This converts the passed word to pig latin
*/
public String latinWord(String word)
{
String lWord = "";
String beforeVowel = "";
String afterVowel = "";
boolean caps = false;
char first = word.charAt(0);
if(first > 'A' && first < 'Z')
{
first = Character.toLowerCase(first); //If the first char is capital, we need to account for this
caps = true;
}
if(containsNoVowels(word))
lWord = Character.toUpperCase(first) + word.substring(1) + "ay"; //If we have no vowels
if(word.charAt(0) == 'A' || word.charAt(0) == 'a' || word.charAt(0) == 'E' || word.charAt(0) == 'e' || word.charAt(0) == 'I' || word.charAt(0) == '0'
|| word.charAt(0) == 'O' || word.charAt(0) == 'O' || word.charAt(0) == 'o' || word.charAt(0) == 'U' || word.charAt(0) == 'u')
{
lWord = Character.toUpperCase(first) + word.substring(1) + "yay"; //If the first char is a vowel
}
if(word.charAt(0) != 'A' || word.charAt(0) != 'a' || word.charAt(0) != 'E' || word.charAt(0) != 'e' || word.charAt(0) != 'I' || word.charAt(0) != '0'
|| word.charAt(0) != 'O' || word.charAt(0) != 'O' || word.charAt(0) != 'o' || word.charAt(0) != 'U' || word.charAt(0) != 'u')
{ //If the first letter isnt a vowel but we do have a vowel in the word
for(int m = 0; m < word.length(); m++)//if we have a vowel in the word but it doesn't start with a vowel
{
if(word.charAt(m) == 'A' || word.charAt(m) == 'a' || word.charAt(m) == 'E' || word.charAt(m) == 'e' || word.charAt(m) == 'I' || word.charAt(m) == 'm'
|| word.charAt(m) == 'O' || word.charAt(m) == 'O' || word.charAt(m) == 'o' || word.charAt(m) == 'U' || word.charAt(m) == 'u')
{
for(int l = 0; l < word.substring(m).length(); l++)
{
afterVowel += word.substring(m).charAt(l); //Build the part after the first vowel
}
m += word.length();
}
else
beforeVowel += word.charAt(m);
}
if(caps == false)
lWord = afterVowel + beforeVowel + "ay";
else
{
first = Character.toUpperCase(afterVowel.charAt(0));
}
}
return lWord;
}
/*
* This function checks the string letter by letter to see if any of the letters are vowels.If there are none it returns true
*/
public boolean containsNoVowels(String wrd)
{
for(int h = 0; h < wrd.length(); h++)
{
if(wrd.charAt(h) == 'A' || wrd.charAt(h) == 'a' || wrd.charAt(h) == 'E' || wrd.charAt(h) == 'e' || wrd.charAt(h) == 'I' || wrd.charAt(h) == 'h'
|| wrd.charAt(h) == 'O' || wrd.charAt(h) == 'O' || wrd.charAt(h) == 'o' || wrd.charAt(h) == 'U' || wrd.charAt(h) == 'u')
return false;
else
return true;
}
return false;
}
I think the error lies inside your second for loop within pigLatin():
for (int j = 0; j < x.substring(i).length(); j++) // find the next character that isn't a letter
{
if(x.charAt(i) < 65 || x.charAt(i) > 90 && x.charAt(i) < 97 || x.charAt(i) > 122)
The last line shown above starts checking at char i. This is the same char you just checked in the outer loop. So the test will succeed. And I think the logic breaks down either in this iteration or a subsequent one.
I think what you want is:
for(int j = 1; j < x.substring(i).length(); j++)
{
if (x.charAt(j) < 65 || x.charAt(j) > 90 && x.charAt(j) < 97 || x.charAt(j) > 122)
Note, there are two changes:
Initialise j at 1 to test the next character in the for statement
Test the jth character, not the ith in the if statement

How do I write a program that counts the number of words which has at least 2 vowels in it?

I could only find the words with 'x' number of vowels. I need to find number of words containing at least 2 vowel.
public static void main(String[] args) {
int counter2 =0;
String acc = JOptionPane.showInputDialog("Enter a string:");
String[] words = acc.split(" ");
for(String word : words){
int counter =0;
word = word.toLowerCase();
for (int i =0; i < word.length(); i++){
char x = word.charAt(i);
if(x == 'a' || x == 'e' || x == 'i' ||
x == 'o' || x == 'u'){
counter++;
}
}
if (counter >= 2) {
System.out.println(counter);
You could define another counter which will count number of words as you are counting just vowel count. So something like:
int numberOfWords = 0;
... for loop
if (counter >= 2) {
numberOfWords++;
}
// print numberOfWords
In your code you're counting the number of vowels and if its >=2, you're printing the vowel counter value instead of printing word count. You can keep track of word counts in the same if condition
public static void main(String[] args) {
int counter2 =0;
String acc = JOptionPane.showInputDialog("Enter a string:");
String[] words = acc.split(" ");
int wordsWithVowels = 0;
for(String word : words){
int counter =0;
int sum=0;
word = word.toLowerCase();
for (int i =0; i < word.length(); i++){
char x = word.charAt(i);
if(x == 'a' || x == 'e' || x == 'i' ||
x == 'o' || x == 'u'){
counter++;
}
} // end of inner for loop
if (counter >= 2) {
wordsWithVowels++;
}
} // // end of outer for loop
System.out.println("Number of words with 2 or more vowels "+wordsWithVowels);
} // end of main
you can use a count variable and increment it when your counter variable has a value greater equal than 2 . you will get count of words.
And you also might wanna take capital vowels into consideration also.

Categories

Resources