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");
Related
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.
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"))
my goal is to take the first letter of a word and moving it to the end until the first letter is a vowel. this is pig latin
System.out.println("Enter a word: ");
String word = keyboard.nextLine();
String y = word.substring(0,1);
String z = word.substring(1);
char x = Character.toLowerCase(word.charAt(0));
if ((x=='a') || (x=='e') || (x=='i') || (x=='o') || (x=='u')) {
System.out.println(word + "ay ");
}
while ((x!='a') || (x!='e') || (x!='i') || (x!='o') || (x!='u')) {
String s = z+y;
System.out.println(s);
}
Your error is that in your while loop, you never update the value of x. Therefore the program never terminates. In an effort to make your "pig latin" more readable and easier to debug, you should consider breaking your program into methods.
Such as:
public static boolean isVowel(char input){
input = Character.toLowerCase(input);
return ((input=='a') || (input=='e') || (input=='i') || (input=='o') || (input=='u'));
}
So that then you would be able to do:
System.out.println("Enter a word: ");
String word = keyboard.nextLine();
while (!isVowel(word.charAt(0))){ //while the first character isn't a vowel do this:
word = word.substring(1) + word.charAt(0);
}
System.out.println(word);
However beware that if there is no vowel this program will still run into a infinite loop.
Without methods the code would look something like this:
System.out.println("Enter a word: ");
String word = keyboard.nextLine();
char currentChar = Character.toLowerCase(word.charAt(0));
while (!((currentChar=='a') || (currentChar=='e') || (currentChar=='i') || (currentChar=='o') || (currentChar=='u'))){ //while the first character isn't a vowel do this:
word = word.substring(1) + word.charAt(0);
currentChar = Character.toLowerCase(word.charAt(0));
}
System.out.println(word);
Hope this helps :)
You keep doing checks on the variable x, but you are not updating its value in the loop body. Therefore, the condition keeps being verified.
In other words
First iteration: Is x different from a vowel?
If so, build the s string and print it
Second iteration: Is x different from a vowel?
Same as 2... and so on.
So I have this program I need to write. I'm, supposed to get an input string from a user and then print out how many capital letters and how many lowercased letters are in the string. I've looked everywhere in the book that I have and I just can't seem to find anything about how to print out the uppercase and lowercase letters. I've been doing a lot of googling as well and I couldn't find anything useful.
Anyway here's my code:
import java.util.Scanner; //calls out the method to get input from user
public class Verk1 {
public static void main(String args[])
{
Scanner innslattur = new Scanner(System.in); //input gotten from user
System.out.println("Sláðu inn textabrot í há- og lágstöfum.");
System.out.println("Forritið mun þá segja þér hve margir stafir eru af hverri gerð.");
System.out.println("Textabrot: ");
//The printouts before tell the user to enter in a string, the program will then print out //how many upper- and lowercase letters there are.
String strengur = innslattur.nextLine();
String hastafir = "";
for (int i=0; i<hastafir.length();i++);
{
System.out.println("Í textabrotinu eru " + hastafir + " hástafir");
}
}
}
I know the code is faulty/doesn't work, but do any of you know how I get the number of uppercase- lowercase letters to print them out?
Thanks in advance!
Cheers
I haven't tested it but I would look to do something like this.
String text = "This IS My TEXT StrinG";
int upperCaseCounter = 0;
int lowerCaseCounter = 0;
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
upperCaseCounter++;
}
else if(Character.isLowerCase(text.charAt(i)))
{
lowerCaseCounter++;
}
}
System.out.println("Total Uppercase Characters: " + upperCaseCounter);
System.out.println("Total Lowercase Characters: " + lowerCaseCounter);
You can do their fairly easily if you convert the string to a char[] first. You can then use the isUpperCase(char c) for each character in the string. http://www.tutorialspoint.com/java/character_isuppercase.htm
For some strange reason your for loop is referring to an empty string you've just declared, rather than the string you just read in from the user. However, if you change that, inside your loop you can get at the individual characters in the string with strengur.charAt(i) and you can test whether a letter is capital with Character.isUpperCase(ch) and you can check for a lower case letter with Character.isLowerCase(ch).
public void printCapsAndLowercaseCounts(String s) {
int uppercase = 0;
int lowercase = 0;
if (s != null) {
String s1 = s.toUpperCase();
String s2 = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s1.charAt(i) ^ s.charAt(i) == s2.charAt(i)) {
if (s.charAt(i) == s1.charAt(i)) uppercase++;
else lowercase++;
}
}
}
System.out.println(uppercase + " " + lowercase);
}
Seems like this would do the trick, assuming you're not doing it an excessive amount. Just use a temporary string, and get the difference between the two:
int capLetterCount = originalString.length() - originalString.replaceAll("[A-Z]", "").length();
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.