I Have a String S= "I love bangalore " It should print the letters between 2 vowels like below :
1.v
2.ng
3.l
4.r
Note : I am able to print if there only 1 letter b/w 2 vowels not more than that.
This what I have tried :
String a = "i love bangalore";
String[] words = a.split(" ");
for (String word : words) {
for (int i = 1; i < word.length(); i++) {
if (word.length() > 3) {
if(i==word.length()-1){
System.out.println("skip");
}
else if(checkIsVowel(word.charAt(i))&&!checkIsVowel(word.charAt(i+1))&&checkIsVowel(word.charAt(i+2))){
System.out.println(word.charAt(i+1));
}
}
}
}
The way you are trying is not right because
You are checking for length 3 or more which is not true
You are checking for vowel, normal alphabet, vowel which is also not true. ex: angl
Here is one way to solve it
String[] words = str.split(" ");
for (String word : words) {
int firstVowelIndex = -1;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (checkIsVowel(ch)) {
// if vowel index is found again and there exists at least one character between the two vowels
if (firstVowelIndex != -1 && i - firstVowelIndex != 0) {
System.out.println(word.substring(firstVowelIndex + 1, i));
}
// vowel index is assigned
firstVowelIndex = i;
}
}
}
Input:
i love bangalore
Output:
v
ng
l
r
The best way to do this is as follows:
Find a vowel, non-vowel pair.
Set result to non-vowel.
Continue to find non-vowels, appending to result
When a vowel is encountered, either print or save result
remembering you are at a vowel, go back to 1 and repeat until word is exhausted.
Make certain you use print statements to help debug your program.
Related
Im trying to create a piece of code that counts the number of times a character is said in a sentence when inputted. The teacher for the assignment gave us an outline of what is should be but it doesnt make sense.
int numOfE = 0; //a counter
for (int index = 0; index < line.length(); index++)
{
if(//character_at_index == 'e' or == 'E')
numOfE++;
}
The method you're looking for is charAt. Here's an example:
String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f
For more information, see the Java documentation on String.charAt.
If you don't want the result as a char data type, but rather as a string, you would use the Character.toString method:
String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f
For coding problems like this, the commented out part (after the //) is typically where you would insert your answer. In this case you will replace
//character_at_index == 'e' or =='E'
with your clever bit of code logic.
Hint: charAt()
The assignment asks you to write a condition in the if statement that will determine if a character at position index matches the letter e or E. You have to translate that to code.
To do this, you need to know how to retrieve a character at a given position in a string and how to compare two characters.
If you are using Java 8, it can be simply achieved (Stream and Lambda) as follows:
String someString = "ExcellencE";
long count = someString.chars().filter(ch -> (ch == 'E' || ch == 'e')).count();
System.out.println(count);
Console output:
4
I figured out that with a char method it counts every e in a sentence. I had it formatted incorrectly so it counted every letter instead of just e's
int countChar;
char e;
String str;
int count = 0;
System.out.println("input your sentence:");
str = in.nextLine();
str = in.nextLine();
for(i=0; i < str.length(); i++)
{ if(str.charAt(i) == 'e')
count++;
}
System.out.println("The sentence contains" + ' ' + count + ' ' + "E and e");
I have created a program that allows the user to enter 5 words. These words
are stored into a string array. When the user is finished, the number of times a word beginning with the letter ‘B’ was entered, lower or uppercase is displayed. Now I also have to re-state the B words.
So this is the code I have so far that finds how many of the words entered starts with "b"
int fromIndex = 0;
int count = 0;
String words[] = new String [5];
for (int x = 0 ; x <= words.length - 1 ; x = x + 1)
{
System.out.print ("Please enter a word: ");
words [x] = kbi.readLine ();
fromIndex = 0;
words [x] = words [x].toLowerCase ();
fromIndex = words [x].indexOf ("b", fromIndex);
if (fromIndex == 0) // STARTS WITH B
{
count++;
}
}
System.out.println ("You entered " + count + " 'B' words and they were: ");
I was thinking that I could use an if statement to print the b words. Like:
if (words.charAt(0) == "b")
{
System.out.println (words);
}
but that doesn't really seem to work and I didn't really think it would, I'm kind of at a loss of what to do.
I hope I can receive some help on this, thank you in advance.
in your code words is not an String(it is an array of String) so it doesn't have charAt method that you used above. you have 5 String in your words array so if you want to write all String in your array which start with character 'b' you should loop through your array and print all that start with 'b', like this:
for(String str : words){
if (str.charAt(0) == 'b'){
System.out.println(str);
}
some tips:
in java 7 String has startsWith method that you can use. if you are using java 6 check if it has it too:
for(String str : words){
if (str.startsWith("b", 0)){
System.out.println(str);
}
It's because charAt returns char instead of String, so you would have to change your comparison:
if (words.charAt(0) == 'b')
Other possibility would be to use regex "b.*" or even easier - String comes with startsWith method, so you can simply do this:
if (words.startsWith("b"))
14.11 (Searching Strings) Write an application that inputs a line of text and a search character and uses String method indexOf to determine the number of occurrences of the character in the text.
14.12 (Searching Strings) Write an application based on the application in Exercise 14.11 that inputs a line of text and uses String method indexOf to determine the total number of occurrences of each letter of the alphabet in the text. Uppercase and lowercase letters should be counted together. Store the totals for each letter in an array, and print the values in tabular format after the totals have been determined.
My problem now is that how can I determine occurrence of each letter in a word. For example, the word "occurrence", how many times each letter occurred in this word.
I've written my code to the best of my understanding, and my code can display the characters and returns their indexes in a tabular form. But that is not exactly what the questions required.
import java.util.*;
public class Searching
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Text: ");
String text1 = input.nextLine();
char[] text2 = text1.toCharArray();
System.out.println("Character Index");
for(int i = 0; i < text2.length; i++)
{
System.out.printf("%s%12d%n", text2[i],text1.indexOf(text2[i], i));
}
}
}
I want the actual output to be in a tabular format. The word "occurrence", my code should display each letter and how many times it occurred.
LETTER FREQUENCY
o 1
c 3
u 1
r 2
e 2
n 1
Is it ok if you used a HashMap? Here's the solution for 14.12:
Scanner in = new Scanner(System.in);
System.out.print("Enter text: ");
//So we only have to find lower case chars
String input = in.nextLine().toLowerCase();
//Add every single character in the word
//We use a LinkedHashMap instead of a HashMap to retain character order during printing.
LinkedHashMap<Character, Integer> characterCount = new LinkedHashMap<>();
for(int i = 0; i < input.length(); i++) {
characterCount.put(input.charAt(i), 0);
}
//Iterate from every character ranging from a - z
//It would be more ideal to iterate only over the characters
//in the word. But your requirement asked to iterate over the alphabet.
for(int i = 'a'; i <= 'z'; i++) {
//This is the character we are currently searching for
Character searchingFor = (char)i;
int startingIndex = 0; int foundIndex = 0;
//Search for the character in the string FROM a specfic index (startingIndex in this case)
//We update startingIndex to a bigger index in the string everytime we find the character.
while((foundIndex = input.indexOf(searchingFor, startingIndex)) != -1) {
//it must be the index+1 so the next time it checks after the found character.
//without the +1, it's an infinite loop.
startingIndex = foundIndex + 1;
//Update count to the current value + 1
characterCount.put(searchingFor, characterCount.get(searchingFor) + 1);
}
}
//Print the results
for(Character c : characterCount.keySet()) {
System.out.printf("%s%12d%n", c, characterCount.get(c));
}
in.close();
Console output for the word "occurence":
Enter text: occurence
o 1
c 3
u 1
r 1
e 2
n 1
I'm just starting out with Java so I'm pretty new to this programming language. I've been looking at similar problems for hours now but nothing specific enough to follow that seems to help me.
How do I check to see if the last letter of the first word is the same as the next word's first letter? For example, the user inputs: Chocolate Elephant Toronto. Chocolate's last letter is 'e', which is the first letter of elephant, and then the last letter of elephant is 't', which is the first letter of Toronto.
I want to make it so if all the words correctly follow one another, it will print something like "They all match" and if not, then "second word does not follow first word".
I'm just looking for tips on how to do this if the user decides to enter a different amount of words each time to check. I'm guessing I'll need a String Array, but can I still solve this using charAt?
You can use a method like the following:
private static boolean wordCheck(String[] words) {
if(words.length < 2) {
return true; //check what to return if only 1 word is passed
}
for(int i = 1; i < words.length; i++) {
String currentWord = words[i].toLowerCase();
String previousWord = words[i - 1].toLowerCase();
if(!currentWord.startsWith(previousWord.substring(
previousWord.length() - 1))) {
return false;
}
}
return true;
}
It just checks each word's beginning against its preceding word's ending.
wordCheck("Chocolate Elephant Toronto".split(" ")) //returns true
wordCheck("Chocolate Elephant oronto".split(" ")) //returns false
Remember to validate the words that you send to the method. The above doesn't ensure indexes are valid, nulls and 0-length strings can cause exceptions.
Try something like this:
public String checkWords(String phrase){
if(phrase == null){
return "Phrase must not be null";
}
String[] words = phrase.toLowerCase().split(" ");
if(words.length < 2){
return "At least 2 words!";
}
for (int i = 0; i < (words.length - 1); i++) {
String firstWord = words[i].trim();
char firstWordlastLetter = firstWord.charAt(firstWord.length()-1);
String secondWord = words[i+1].trim();
char secondWordFirstLetter = secondWord.charAt(0);
if(firstWordlastLetter!=secondWordFirstLetter){
return String.format("Word %d does not follow word %d", i+1, i);
}
}
return "They all match";
}
I have to find the last word in a string and can't understand why my code isn't working. This is what I have:
int i, length;
String j, lastWord;
String word = "We the people of the United States in order to form a more perfect union";
length = word.length();
for (i = length - 1; i > 0; i--)
{
j = word.substring(i, i + 1);
if (j.equals(" ") == true);
{
lastWord = word.substring(i);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
}
However, when I run it, it prints the last letter. I know I could use
String lastWord = word.substring(word.lastIndexOf(" ") + 1)
But I'm pretty sure my teacher doesn't want me to do it this way. Any help?
You need to remove the ; after the if to make it work:
if (j.equals(" ")) // <== No semicolon, and no == true
{
lastWord = word.substring(i);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
You do not need == true for booleans inside control statements, either.
Finally, making single-character substrings is more expensive than using single characters. Consider using charAt(i) instead:
if (word.charAt(i) == ' ') // Single quotes mean one character
{
lastWord = word.substring(i+1);
System.out.println("Last word: " + lastWord);
break; // there is a better way to stop the loop
}
You've terminated the if statement. It should be,
if(j.equals(" "))
{
...
}
Just take that ; from if (j.equals(" ") == true); out.
Your code remade cleaner:
String word = "We the people of the United States in order to form a more perfect union";
for (int i = word.length() - 1; i > 0; i--)
if (word.charAt(i - 1) == ' ') {
System.out.println("Last word: " + word.substring(i));
break; // To stop the loop
}
Minimum iterations.
Convert the string to char array and look for space from the end of array. Don't forget to remove white spaces from the end using trim() as they could be counted as separate words.
s = s.trim();
char[] c = s.toCharArray();
for(int i=0; i<c.length; i++)
{
if(c[c.length-1-i]==' ')
{
return s.substring(c.length-1-i);
}
}
return s;
This also covers the null string case.
Another alternative using split.
s = s.trim();
String[] strs = new s.split(' ');
return str[str.length-1];
The semicolon after your "if" statement means "do nothing." Also, the "== true" is redundant. Lastly, you don't want to include the space you just found. Try this:
for (i = length - 1; i > 0; i--)
{
j = word.substring(i, i + 1);
if (j.equals(" "))
{
lastWord = word.substring(i + 1);
System.out.println("Last word: " + lastWord);
i = -1; //to stop the loop
}
}
There's a method for strings to split up at http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
A good, fast and easier way would be:
word = word.split(" ")[word.length-1];
split() returns an array of substrings based on " ". Since an array starts with 0, its last element is the length of the array - 1.