Program to count vowels in several inputs of strings - java

What this programme does is;
Prompts for number of testcases,
User then inputs lines of strings which are the test case.
Program is to count the number of vowels in each test case.
then print out the each test case.
btw for this particular program "y" is also a vowel
For instance;
Number of test:
4
githsajklu
bsa uiqsacva
o h qi samsauq sajahhsa
skajayyosak
answer:
5 4 13 2
The problem is that the program doesnt read the last line/input. it just brings the count for the first 3 inputs but not the last. I hope I am clear enough
import java.util.Scanner;
/*
* Counts number of Vowels in each line
*/
public class VowelCount {
/*
*
*/
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
//prompt user for number of test case
System.out.println("Type in number of Test Cases");
int testcases = input.nextInt();
String[] line = new String[testcases];
String newline;
for(int i=0; i<testcases; i++)
{
//initialize input to line 1,2,3 e.t.c
line[i] = input2.nextLine();
//remove all white spaces
newline =line[i].replaceAll(" ", "");
display(testcases, newline);
}
}
/*
* counts how many vowels are in eace line of input
*/
public static int Counter(String input)
{
//start count from 0;
int counter = 0;
for(int i = 0; i<input.length(); i++)
{
//set character at position i to Dstr
char dStr = input.charAt(i);
//compare if dstr is a vowel
if(dStr == 'i' || dStr == 'u' || dStr == 'o' || dStr == 'a' || dStr == 'e' || dStr == 'y')
{
//increase when characte is a vowel
counter++;
}
}
//return the last count
return counter;
}
/*
* diplay the total count;
*/
public static void display(int testcases, String input)
{
System.out.print(" "+Counter(input));
}
}

Do a scan.nextLine() after you read the amount of test cases. Don't know why it works like that, someone feel free to explain, but if you're reading a an int, then a string, you can either do
int n = Integer.parseInt(scan.nextLine());
or
int n = scan.nextInt();
scan.nextLine();
Also, I know you didn't ask, but here's a much simpler way to count the amount of vowels.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
scan.nextLine();
for(int i = 0; i < n; i++){
String str = scan.nextLine();
System.out.println(str.replaceAll("[^AEIOUaeiouYy]", "").length());
}
}
What that does is erase everything that is not a vowel (and y), and prints the length of it. Really not sure if it's faster, but it's a lot simpler.

Actually, here I'm testing and it is working just fine, it is getting exactly how many inputs I asked for.
My console:
Type in number of Test Cases
4
werty
2
sdfghj
0
xdcfvgh
0
xsdfgh
0

Sometimes, having less code can make things clearer:
void printVowelCount(String text) {
System.out.println(text.replaceAll("[^aeiouAEIOU]", "").length());
}

Related

Trying to find the numbers in a line of user input, and then save them to an array stack

For this problem, I am working on finding numbers within a formula (ex. 60 / 30) and save them to a stack. I am currently using the .isDigit method to determine whether a character is a digit or not, and then am checking each character after it to see if it is a multi-digit number or not (ex. 600 or 34). I use a substring method to cut each number from the formula and then a push method obviously to save it into the arraystack. I'm getting index out of bounds errors and don't know where I went wrong. here is the code:
public static void main (String[]args) {
System.out.println("input your formula ");
Scanner scan = new Scanner (System.in);
String input;
input = scan.nextLine();
scan.close();
System.out.println("input: " + input);
ArrayStack st = new ArrayStack();
for(int j = 0; j < input.length(); j++) {
if (Character.isDigit(input.charAt(j))) {
int cur = 0;
while (input.charAt(j + cur) != ' ') {
cur += 1;
String number = input.substring(j,cur);
st.push(number);
break;
}
}
}
while (!st.isEmpty())
{
System.out.println(st.peek());
st.pop();
}
}
}
I tried and expected to get the numbers out of the formula and put them into a stack, then print them out.

Method to check if the string contains certain elements that accepts a parameter String

I am a student and kind of new to Java. For my homework I have to:
Ask the user to input a number (at least 7) using a do while loop.
Using a for loop I am required to ask the user to input that number of words.
Then I have to check if one of the words fulfills the given conditions:
The word must:
Start with an uppercase letter
End with a number
Contain the word "cse".
I am asked to create a method inside some code homework that does a specific task, the method should check all the required conditions, the name of the method should be countTest and it accepts the String as a parameter.
I will show you my code but I don't know how to create this specific method.
Output format
System.out.println("There as a total number of words " + count + " and
the ones that fulfill the condition are: " + condition);
The problem is, I dont know how to create the method or constructor or whatever it is called that calls all of the 3 methods inside it, and then connect that particular method to the main method!
I hope you guys can understand I am new to this, thank you in advance!
public class D6_6 {
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do{
if(number<7){
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while(number<7);
sc.nextLine();
String str;
for(int i =0; i<number; i++){
System.out.println("Type a word");
str = sc.nextLine();
count++;
}
}
public boolean countTest(String str) {
}```
To check if the word start with an uppercase:
You can do that by first selecting the character you want to check by str.charAt(0). This will return a char that is the first letter of the input str.
To check if this char is an uppercase letter, you can easily use char.isUppercase(). This will return a boolean. You have to replace char by the name of the variable were you put the char of str.charAt(0) in.
To check if the last character is a number:
You can do that again by first selecting the last character by str.charAt(str.length()-1), were string.length-1 is the number of the last character.
To check if this character is a number, you can use the ascii table. Every character has it's own number. So if you want to check if your character is between 0 and 9, you can use char >= 48 || char <= 57 (look up in the ascii table). Again, char is the name of the variable were you put the char of str.charAt(str.length()-1) in.
To check if the word contains "cse":
There is a very easy method for that: str.contains("cse") will return a boolean that is true when "cse" is in the word and false when the word does not contain "cse".
I hope it is clear for you now!
I think I did it, thank you guys very much, I appreciate it!
public class D6_6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type a number that is at least 7");
int number = sc.nextInt();
int count = 0;
int condition = 0;
do {
if (number < 7) {
System.out.println("You should type a number that is at least 7 or higher");
number = sc.nextInt();
}
}
while (number < 7);
sc.nextLine();
String str;
for (int i = 0; i < number; i++) {
System.out.println("Type a word");
str = sc.nextLine();
count++;
if((countTest(str))){
condition++;
}
}
if(count == 0){
System.out.println("No words typed");
} else {
System.out.println("Total number of words typed: " + count + ", which fulfill the condition: "+ condition);
}
}
public static boolean countTest(String str) {
return Character.isUpperCase(str.charAt(0)) && str.charAt(str.length() - 1) >= 48 || str.charAt(str.length() - 1) <= 57 || str.contains("cse");
}
}```

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

String index out of range error help. Pig latin project

I'm doing an assignment that converts a string sentence into pig latin.
I've planned and written all the code but I get this error:
String index is out of range
Below is my code:
import java.util.*;
public class project1d {
public static void main(String[] args){
System.out.println("This is a pig latin translator. Enter a sentence to convert.");
Scanner console = new Scanner(System.in);
pigLat(console);
}
public static void pigLat(Scanner console){
String sentence = console.next();
int start = 0;
int end = 0;
int counter =0;
while(sentence.length()>0){
while(end<sentence.length()-1){
while(sentence.charAt(counter+1)!=' '){
counter++;
end = counter;
}
String word = sentence.substring(start,end);
int index= 0;
char letter= word.charAt(index);
while (letter != 'a' || letter != 'e' || letter != 'i' ||
letter != 'o' || letter != 'u'){
index++;
}
System.out.print(word.substring(index,word.length()-1)+"-");
System.out.print(word.substring(0,index-1)+"ay");
counter++;
start=end+1;
}
System.out.println("Do you wanna put in another? Press ENTER to quit");
sentence = console.next();
}
}
}
I think the third while loop is increasing one too many times, but I can't figure out how to fix this or if that's even the problem.
The actual java errors are listed below:
- java.lang.StringIndexOutOfBoundsException: String index out of range: 4
- at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
- at java.base/java.lang.String.charAt(String.java:693)
- at project1d.pigLat(project1d.java:15)
- at project1d.main(project1d.java:6)
Any help is appreciated.
Unfortunately, there are many things wrong with the code, aside of whether it does what it's intended to do or not.
You're increasing the indexes and checking the value without confirming whether those indexes are valid.
You are not clearing the variables before using them again after the first iteration of the whole thing.
You're increasing the index but you got an infinite loop at the letter check because you're not changing the letter when you increase the index.
The letter check is checking conditions that overlap - letter!= a || letter!=e will always be true, thus this makes it an infinite loop too.
As Andy pointed out: String sentence = console.next(); will only read a single word. Use nextLine instead.
Please try:
public static void pigLat(Scanner console){
String sentence = console.next();
int start = 0;
int end = 0;
int counter =0;
while(sentence.length()>0){
start = 0; end = 0; counter = 0;
while(end<sentence.length()-1){
while(sentence.length()>counter+1 && sentence.charAt(counter+1)!=' '){
counter++;
end = counter;
}
String word = sentence.substring(start,end);
if(word.length()>0){
int index = 0;
char letter = word.charAt(index);
while(index+1<word.lenght() && letter != 'a' && letter != 'e' && letter != 'i' && letter != 'o' && letter != 'u'){
index++;
letter = word.charAt(index);
}
System.out.print(word.substring(index,word.length()-1)+"-");
System.out.print(word.substring(0,index-1)+"ay");
}
counter++;
start=end+1;
}
System.out.println("Do you wanna put in another? Press ENTER to quit");
sentence = console.nextLine();
}
It's just natural that your code has some mistakes, as you're still learning how to do that properly. Keep it up ;)

I need to create a program that allows a user to input any string. The program must determine how many vowels and words are within the string

I am currently stuck on the first loop of the code. I'm having a difficult time comparing the character at an index within the string to the first vowel a (Keeps saying that char cannot be dereferenced...).
I would just like to know how to properly compare any letter within the string to any vowels (a, e, i, o, u). I would also like to know if I can compare a certain letter within the string to the entire array, or would I just have to compare to every individual vowel??
import java.util.*;
class StringCount {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String user;
int charCount;
char[] vowel = {'a', 'e', 'i', 'o', 'u'};
System.out.println("Please enter any string!");
user = input.nextLine();
charCount = user.length();
for (int i = 0; i < charCount; i++) {
if(user.charAt(i).equals('a') {
}
}
}
}
You are missing a couple of things here:
a. Character can be in uppercase or lowercase.
b. Word seperators, they may be comma , space, etc.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class WaitTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String user;
int charCount;
List<Character> vowels = new ArrayList();
//add all vowels to list inclusing uppercase
a,e,i,o,u,A,E,I,O,U
vowels.add('a');
vowels.add('e');
List<Character> wordSeperators = new ArrayList();
//add your word seperators here
wordSeperators.add(' ');
wordSeperators.add(',');
System.out.println("Please enter any string!");
user = input.nextLine();
charCount = user.length();
int vowelCount=0,wordCount=0;
for (int i = 0; i < charCount; i++) {
char c= user.charAt(i);
if(vowels.contains(c)) {
vowelCount++;
}else if (wordSeperators.contains(c)){
wordCount++;
}
}
}
}
If you just want to check your user enter a word with a char in your list you could use Java.lang.String.contains() Method with your char list in the loop
If u want to check your user enter is exctely a char in your list, you could use Java.lang.String.equal() Method with in a loop
Another possible solution:
if (Arrays.binarySearch(vowel, user.charAt(i)) >= 0) {
}
Update:
equals() is used for Objects (String, Integer, etc...)
For primitives like int, boolean, char etc, you have to use ==
Try with this.
public static void main(String[] args) {
int count =0;
String user;
Scanner input = new Scanner(System.in);
System.out.println("Please enter any string!");
user = input.nextLine();
System.out.println(user);
int inputLength = user.length();
try{
for (int i = 0; i < inputLength; i++) {
char letter = user.charAt(i);
if(letter=='a'||letter=='e'||letter=='i'||letter=='o'||letter=='u') {
count +=1;
}
}
}catch (Exception e) {
// TODO: handle exception
}
System.out.println("FINAL COUNT "+count);
}
You will need to modify your code to compare every input char with your vowel array.
for (int i = 0; i < charCount; i++) {
for (char v : vowel) {
if(user.charAt(i) == v {
//here is what you do if a vowel <v> is found
}
}
}
Hope this helps.
My instructor isn't too strict on the manner in which we complete this as we are fairly new to programming. I tampered with my code and found a solution. I understand it may not be the best solution, but for the most part, as long as proper punctuation is used within the String, then the word count as well as the vowel count do go up as desired.
Most of the answers I received were a little advanced for me. We haven't covered a lot of these concepts, but thank you guys so much. Someone pointed out that I was using ".equals" to compare a single character instead of using the "==". This solution helped me the most!!
If anyone can add on to my solution to allow ANY user input be converted into the correct word count and vowel count then thank you!!
ex. 1 (States the correct word count and vowel count):
String: "Let us go over there!"
vowels: 7
words: 5
ex. 2 (States the incorrect word count and vowel count):
These are the values when no punctuation is used
String: "Let us go over there"
vowels: 7
words: 4
import java.util.*;
class StringCount {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String user;
int s, charCount, wordCount, vowelCount;
char[] vowel = {'a', 'e', 'i', 'o', 'u',};
char[] punct = {' ', '.', ';','?', '!', '-'};
s = 0;
wordCount = 0;
vowelCount = 0;
System.out.println("Please enter any string!");
user = input.nextLine();
user = user.toLowerCase();
charCount = user.length();
for (int i = 0; i < charCount; i++) {
if(user.charAt(i) == vowel[0] ||
user.charAt(i) == vowel[1] ||
user.charAt(i) == vowel[2] ||
user.charAt(i) == vowel[3] ||
user.charAt(i) == vowel[4])
vowelCount++;
if(user.charAt(i) == punct[0] ||
user.charAt(i) == punct[1] ||
user.charAt(i) == punct[2] ||
user.charAt(i) == punct[3] ||
user.charAt(i) == punct[4] ||
user.charAt(i) == punct[5])
wordCount++;
}
System.out.println("Vowels: " + vowelCount);
System.out.println("Words: " + wordCount);
}
}

Categories

Resources