Hey this is my first time posting! I got my program to print out the vowels from an input from user but I feel like I have repeated myself a lot in the for loop. Is there a quicker way to do this? Also is this code readable and in the correct format?
import java.util.Scanner;
public class Task09 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String vowels ="";
//input from user
String answer= input.next()
//loop to find vowels
for(int i = 0 ;i<answer.length();i++)
{
char answerPosition = answer.charAt(i);
//checks if there are vowels in code
if (answerPosition =='a'
||answerPosition =='e'
||answerPosition =='i'
||answerPosition =='o'
||answerPosition =='u'
||answerPosition =='A'
||answerPosition =='I'
||answerPosition =='O'
||answerPosition =='U')
{
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}
Try this:
String newString = answer.replaceAll("[^AaeEiIoOuU]", "");
System.out.println(newString);
You wont need for loop as well and your code would be compact and sweet.
You could do:
if ( "aeiouAEIOU".indexOf(answerPosition) >= 0 ) {
vowels += answerPosition + " ";
}
inside the loop.
Additionally, as a matter of style, you might write the iteration slightly differently:
for (char c: answer.toCharArray()) {
if ( "aeiouAEIOU".indexOf(c) >= 0 ) {
vowels += c + " ";
}
}
You can do this way too.
import java.util.Scanner;
public class Hi {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String vowels = "";
// input from user
String answer = input.next();
// loop to find vowels
for (int i = 0; i < answer.length(); i++) {
char answerPosition = answer.charAt(i);
char tempAnsPos = Character.toUpperCase(answer.charAt(i));
// checks if there are vowels in code
if (tempAnsPos == 'A' || tempAnsPos == 'E' || tempAnsPos == 'I' || tempAnsPos == 'O' || tempAnsPos == 'U') {
vowels += answerPosition + " ";
}
}
System.out.println("The vowels are:" + vowels);
input.close();
}
}
Related
I'm making a program for class which prints out the number of vowels in a word and any help would be appreciated. Currently, the program prints out the correct number of vowels but also prints out the print statement, "vowels:" multiple times before. I've tried moving the print statement and the braces around but it says "error: 'else if' without 'if'". I'm completely new to Java so sorry if the solution is in plain sight. Thank you in advance :)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels= 0;
int l;
l= text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i,i+1);
if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0||
wordPRT.compareToIgnoreCase("i")==0
|| wordPRT.compareToIgnoreCase("o")==0
|| wordPRT.compareToIgnoreCase("u")==0){
vowels++;
System.out.println("vowels: " + vowels);
}
else if(vowels<1){
System.out.print("no vowels");
}
}
}
}
You are printing everything in a for loop instead of count vowels and print at the end.
try something like:
int vowelsCounter = 0;
for(...) {
... logic to count the vowels
if(isvowel(string.charAt(i)){
vowelsCountr++;
}
}
if(vowelsCounter > 0 ) {
printSomething
}
else {
print something else
}
Also You should not use subString for this kind of a loop but string.charAt(i)
Move the print statements out of the for loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter text: ");
String text = input.nextLine();
text = text.toLowerCase();
int vowels = 0;
int l;
l = text.length();
for (int i = 1; i < text.length(); i++) {
String wordPRT = text.substring(i, i + 1);
if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
|| wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
|| wordPRT.compareToIgnoreCase("u") == 0) {
vowels++;
}
}
if (vowels >= 1) {
System.out.println("vowels: " + vowels);
} else {
System.out.print("no vowels");
}
}
}
A sample run:
Enter text: Hello
vowels: 2
I want to print the word which is containing maximum number of vowel. But Problem is that last word of sentence which is containing maximum number is not print. please help me solve that problem. My code is below.
When i enter input 'Happy New Year', Output is 'Yea' .But i want i output is 'Year'
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Word : ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for (int i = 0; i < sentence.length(); i++) {
ch = sentence.charAt(i);
if (ch != ' ' && i != (sentence.length() - 1)) {
word += ch;
ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
} else {
if (vowelCount > temp) {
temp = vowelCount;
wordMostVowel = word;
}
word = "";
vowelCount = 0;
}
}
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
}
}
You cut words at spaces (correct), but you also cut at the last character, even if it's not a space (so this character is never dealt with). And that's not correct.
Here is a possibility:
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String sentence = sc.nextLine();
String wordMostVowels = "";
int maxVowelCount = 0;
for (String word : sentence.split(" ")) {
int vowelCount = 0;
for (char c : word.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
wordMostVowels = word;
}
}
System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
}
}
i am having a bit of trouble in implementing charAt with an array. I am a beginner in Java (and this is my only coding experience i suppose).
The objective: To create a program that the user inputs any string, and the total number of vowels are recorded in the output (case sensitive)
example:
Input: charActer
Output:
a = 1
A = 1
e = 1
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
String [] alphabets =
{"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"};
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for(int i=0;i<alphabets.length;i++)
{
if(alphabets.charAt[i] == vowels)
*Note: Program is not complete.
You need to check each character of inputStr (dunno what alphabets is about in your code) and see if it can be found in the vowels string.
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for (int i = 0; i < inputStr.length(); i++) {
if (vowels.indexOf(inputStr.charAt(i)) >= 0) {
found += 1;
}
}
The documentation is helpful if you're having trouble understanding a method or class.
Having said that, there are lots of ways to count vowels in a String.
Your output indicates that you need the counts per vowel per case, and not just the count of all vowels. To do this you will need a map in order to keep track.
Consider something like
String input = "A string with vowels in it";
Map<Character, Integer> counts = new HashMap<≥();
for (int i = 0; i < input.length; i++) {
char c = input.chart(i);
if (c == 'a') {
int tmp = counts.getOrDefault('a', 0);
tmp++;
counts.put('a', tmp);
} else if (c == 'A') {
// same logic as above for uppercase A
} // other else if statements for e, E, i, I, o, O, u, U
}
// the map has all counts per vowel / case
After the map has all counts you can iterate its entry set to print the output you need
for (Map.Entry<Character, Integer> e : counts. entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
If you only need the number of values without breaking it down into which vowels, consider something like (not tested)
String vowels = "AaEeIiOoUu";
String input = "Hello World!";
int numVowels = 0;
for (int i = 0; i < input.length; i++) {
char c = input.charAt(i);
if (vowels.indexOf(c) >= 0) {
numVowels++;
}
}
// do something with numVowels
--
Break the problem into simple steps
Define the vowels to look for
Initialize your counter variable (numVowels)
Loop through the input string and check each character against the ones defined in 1 (vowels).
For each vowel you find, increment your counter variable.
public class Vowels {
public static void main(String[] args) {
Map<Character, Integer> vowels = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: "); //"charActer";
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
Character c = str.charAt(i);
if (c == 'a'
|| c == 'A'
|| c == 'e'
|| c == 'E'
|| c == 'i'
|| c == 'I'
|| c == 'o'
|| c == 'O'
|| c == 'u'
|| c == 'U') {
if (vowels.containsKey(c)) {
vowels.put(c, vowels.get(c) + 1);
} else {
vowels.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : vowels.entrySet()) {
System.out.print(entry.getKey() + "=" + entry.getValue() + " ");
}
}}
Input : charActer
Output : a=1 A=1 e=1
my program currently takes a random word and turns into dashes based on how many letters are in the word. I then determine if a letter guessed is in the word, but I was unable to figure out how to have the correctly guessed letter replace the dashes accordingly. I looked through possible solutions on the site, but was unable to have one work for my current code.
Code:
public String hiddenWord(){
word = randomWord.getRandomWord();
String dashes = word.replaceAll("[^ ]", " _ ");
return dashes;
}
public String guessNotification(){
if(word.indexOf(hv.keyChar)!=-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
letterGuessed = "There is a " + hv.keyChar + " in the word";
}
else if(word.indexOf(hv.keyChar)==-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
letterGuessed = "No " + hv.keyChar + " in the word";
guesses++;
System.out.println(guesses);
}
else{
letterGuessed = "Not a valid letter";
}
return letterGuessed;
}
public void newGame() {
hv.createNotification(this, size);
guesses = 0;
System.out.println(word);
}
}
Here is how the logic of how to replace the appropriate dash with the correct user guess might look
public static String guessNotification(String word, char userGuess, StringBuilder dashes) {
int guessedIndex = word.indexOf(userGuess);
if (guessedIndex != -1 && (userGuess >= 'a' && userGuess <= 'z')) {
letterGuessed = "There is a " + userGuess + " in the word";
dashes.setCharAt(guessedIndex*3+1, userGuess);
}
else if (guessedIndex == -1 && (userGuess >= 'a' && userGuess <= 'z')) {
letterGuessed = "No " + userGuess + " in the word";
guesses++;
}
else {
letterGuessed = "Not a valid letter";
}
return letterGuessed;
}
Comments are all correct. But you may want to see example code: Add an array of correct guesses:
char[] correct = new char[26]; // or more, depends on whether u use non ascii chars
Initialize the array with e.g. ' '. Then replace the dashes:
StringBuilder guessedPart = new StringBuilder;
for (int lc = 0; lc < word.lenght(); lc++) {
for (char c : correct)
if (word.indexOf(lc) = c) guessedPart.append(c);
if (guessedPart.length() < lc) guessedPart.append('_');
String guessedWord = guessedPart.toString();
That should do.
Here's my attempt to write this code but I'm getting lost with a main part.I'm not sure how the loop will know when a new word starts.For now I know only loops and if-else statements.I would really appreciate if you could just push me in a right direction because this problem is way too hard for me.
Rules of pig latin:
1)If a word begins with a vowel,add a dash and "way" to the end.
2)Otherwise,add a dash,move the first letter to the end,and add "ay"
/*Enter a line of text: This is a test.
Input: this is a test.
Output: his-tay is-way a-way est-tay.
*/
import java.util.Scanner;
public class PigLatin
{
public static void main(String[]args)
{
int count;
String input;
char empty = ' ',first;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
input = keyboard.nextLine();
System.out.println();
for(count = 0; count < input.length(); count++)
if(input.charAt(0) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
System.out.print(input.charAt(count + 1) + "-" + input.charAt(0) + "ay");
else if(input.charAt(count) == empty)
first = input.charAt(count + 1)
if(input.charAt(first) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
System.out.print(input.charAt(first + 1) + "-" + input.charAt(first) + "ay");
else if()
System.out.print("-way"); //I'm lost here.
}
}
Try the following:
import java.util.Scanner;
public class PigLatin {
static final char vowelRegex = "^[aeiouy]"; //Is y a vowel?
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
String input = keyboard.nextLine();
String[] words = input.split(' ');
for(int i=0; i<words.length; i++) {
if(words[i].matches(vowelRegex)) {
System.out.print(words[i] + "-way ");
} else {
System.out.println(words[i].substring(1) + words[i].charAt(0) + "-ay ";
}
}
}
}