How to print the word with the most consecutive vowels? - java

Not sure where I'm going wrong in my programming. The goal is to load a file and find the word with the most consecutive vowels. This code is not giving me the correct word. It gives me "aalii" when it should give me "cooeeing" Can anyone please help me?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class manyVowels {
public static void main(String[] args) {
Scanner fileIn = null;
try {
//locate and open file
fileIn = new Scanner(new FileInputStream("words.txt"));
} catch (FileNotFoundException e) {
//if the file cannot be found, the program prints the message and quits
System.out.println("File not found. ");
System.exit(0);
}
String word;
if (fileIn.hasNext()) //if there is another word do as shown below
{
//seek consecutive vowels
word = fileIn.next();
for(int i=0;i <word.length();i++){
if((word.charAt(i) == 'A') ||
(word.charAt(i) == 'E') ||
(word.charAt(i) == 'I') ||
(word.charAt(i) == 'O') ||
(word.charAt(i) == 'U') ||
(word.charAt(i) == 'a') ||
(word.charAt(i) == 'e') ||
(word.charAt(i) == 'i') ||
(word.charAt(i) == 'o') ||
(word.charAt(i) == 'u')) {
//prints the final word with the most consecutive vowels
System.out.println("The word with the most consecutive vowels is: " + word);
System.exit(0);
}
fileIn.close();
}
}}}
UPDATE: I got this far, but now it is saying that line 34 has an "Exception in thread "main" java.lang.NullPointerException"
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class manyVowels {
public static final String wordList = "words.txt";
public static void main(String[] args) {
Scanner fileIn = null;
try {
//locate and open file
fileIn = new Scanner(new FileInputStream("words.txt"));
} catch (FileNotFoundException e) {
//if the file cannot be found, the program prints the message and quits
System.out.println("File not found. ");
System.exit(0);
}
String word = null;
if (fileIn.hasNext()) //if there is another word continue
{
String finalWord = null; // defines the word with most consecutive vowels
int maxVowels = 0;//sets initial value to 0
while (fileIn.hasNext()) {
// for each word in the file
int vowels = 0;
for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
// for each character in the word, and exit early if the word is not long enough to beat maxVowels
if (hasVowels(word.charAt(i))) {
// consonants reset this to 0
vowels++;
} else {
// reached the end of the word so check if the count is higher than maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
vowels = 0;
}
}
// comparing vowels to maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
}
//seek vowels
word = fileIn.next();
for (int i = 0; i < word.length(); i++) {
if
((word.charAt(i) == 'A')
|| (word.charAt(i) == 'E')
|| (word.charAt(i) == 'I')
|| (word.charAt(i) == 'O')
|| (word.charAt(i) == 'U')
|| (word.charAt(i) == 'a')
|| (word.charAt(i) == 'e')
|| (word.charAt(i) == 'i')
|| (word.charAt(i) == 'o')
|| (word.charAt(i) == 'u')) {
//prints the final word with the most consecutive vowels
System.out.println("The word with the most consecutive vowels is: " + word);
System.exit(0);
}
}
}
}
private static boolean hasVowels(char charAt) {
throw new UnsupportedOperationException("Inserted by template."); //NetBeans generated method
}
}

Try writing out your program in plain language, you're not actually checking how many consecutive vowels there are.
Open file
If the file contains a word, continue
For each letter in the first word do:
if the letter is a vowel,
print "The word with the most consecutive vowels is: " + word
exit the program
So you are actually not doing any checking of how many consecutive vowels there are, but rather checking if there is a vowel in the first word.
Try writing up some pseudocode of what you want to do broken up like I did before you try to write the program

Instead of
if (fileIn.hasNext())
use
while(fileIn.hasNext())

Related

How to check for vowels using a helper method and return a string in Java?

I am attempting to use a helper method that checks if all characters in a word are vowels.
I am then attempting to create another method that uses a Scanner as a parameter and will continuously ask the user to enter a word until the user enters a word that contains all vowels. (The word doesn't have to be a word, it could be ieuo).
I cannot figure out how to have the method verify the scanner is all vowels and then return the correct output.
Here is what I have so far:
import java.util.*;
public class LabFinish {
public static void main(String[] args) {
System.out.println("Enter a word: ");
Scanner scan = new Scanner(System.in);
askForWords(scan);
public static boolean isAllVowels(Scanner scan) {
String str = scan.nextLine();
for (int i = 0; i <= str.length(); i++)
if ((str.charAt(i) == 'a') ||
(str.charAt(i) == 'e') ||
(str.charAt(i) == 'i') ||
(str.charAt(i) == 'o') ||
(str.charAt(i) == 'u')) {
return true;
}
return false;
}
public static String askForWords(Scanner scan) {
if (isAllVowels(scan) == true) {
return "Finally all vowels, we are done.";
}
else {
System.out.println("Enter a word: ");
Scanner scan1 = new Scanner(System.in);
if (isAllVowels(scan1) == true) {
return "Finally all vowels, we are done.";
}
else {
return "Enter a word";
}
}
}
Any help with this would be greatly appreciated.
Thank you.
A couple of things that should help you forward:
Merely returning a String from a method doesn't output it anywhere. So, replacing
askForWords(scan);
with
System.out.println(askForWords(scan));
in main() will show you the result of the method.
While you're checking for vowels, you need to iterate through the whole word, instead of stopping at the first vowel you encounter. Using your current code, the easiest fix is to invert the values of the return statements and the truth value of the comparison:
for (int i = 0; i < str.length(); i++) {
if ( !( // <- if the string has any other characters than the ones below, return a falsey
(str.charAt(i) == 'a')
|| (str.charAt(i) == 'e')
|| (str.charAt(i) == 'i')
|| (str.charAt(i) == 'o')
|| (str.charAt(i) == 'u'))) {
return false;
}
}
return true;
You also have some other issues, such as the code only running for a maximum of two input strings (you'd need a loop instead of a single if-else), but these are a bit off-topic for this question.

How can I search for a character in strings without using a loop?

My assignment is: if the user-inputted word has no vowels, then "ay" is added to the end, if it starts with a vowel then it adds "yay" to the end, otherwise if it doesn't meet any of these conditions then the first letter gets moved to the end of the word and "ay" is added to the end. I can't seem to get the last condition to work. For example the word "sad" should output "adsay" but instead it outputs "saday" which means that it is reading and accepting another if statement. I've tried to look up some solutions but all I've gotten are loops and I'd like to avoid loops for this particular assignment. Here is my code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Word: ");
String word = in.nextLine();
int length = word.length();
String word1 = "";
if (word.charAt(0) == 'a' || word.charAt(0) == 'e' || word.charAt(0) == 'i' || word.charAt(0) == 'o' || word.charAt(0) == 'u')
{
word1 = pigLatin(word);
System.out.println("Pig Latin: " + word1);
}
else if (word.indexOf("a") == -1 || word.indexOf("e") == -1 || word.indexOf("i") == -1 || word.indexOf("o") == -1 || word.indexOf("u") == -1)
{
word1 = pigLatin1(word);
System.out.println("Pig Latin: " + word1);
}
else
{
word1 = pigLatin2(word);
System.out.println("Pig Latin: " + word1);
}
}
static String pigLatin(String word)
{
String x = word + "yay";
return x;
}
static String pigLatin1(String word)
{
String x = word + "ay";
return x;
}
static String pigLatin2(String word)
{
char firstLetter = word.charAt(0);
String x = word.substring(1, word.length()) + firstLetter + "ay";
return x;
}
}
The problem lies in your second if statement:
else if (word.indexOf("a") == -1 || word.indexOf("e") == -1 || word.indexOf("i") == -1 || word.indexOf("o") == -1 || word.indexOf("u") == -1)
{
word1 = pigLatin1(word);
System.out.println("Pig Latin: " + word1);
}
Because you're using "or" here (the || operator), your program will enter this block as long as the word doesn't contain "a", or doesn't contain "e", etc. For your test input, "sad" contains "a" but it doesn't contain "e"... so you wind up calling pigLatin1("sad").
Change this if to use "and" instead (the && operator). That way, the word will need to not have every defined vowel, instead of not having at least one defined vowel.
else if (word.indexOf("a") == -1 && word.indexOf("e") == -1 && word.indexOf("i") == -1 && word.indexOf("o") == -1 && word.indexOf("u") == -1)

Java Why do I get this error? Exception in thread "main" java.lang.NullPointerException

This is the code that it is giving me the error for on the line with >>>>>>> I've already looked at this thread Exceptions but I still do not understand what I need to change :( I am a total beginner to programming.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class manyVowels {
public static final String wordList = "words.txt";
public static void main(String[] args) {
Scanner fileIn = null;
try {
//locate and open file
fileIn = new Scanner(new FileInputStream("words.txt"));
} catch (FileNotFoundException e) {
//if the file cannot be found, the program prints the message and quits
System.out.println("File not found. ");
System.exit(0);
}
String word = null;
if (fileIn.hasNext()) //if there is another word continue
{
String finalWord = null; // defines the word with most consecutive vowels
int maxVowels = 0;//sets initial value to 0
while (fileIn.hasNext()) {
// for each word in the file
int vowels = 0;
/*error here-->*/ for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
// for each character in the word, and exit early if the word is not long enough to beat maxVowels
if (hasVowels(word.charAt(i))) {
// consonants reset this to 0
vowels++;
} else {
// reached the end of the word so check if the count is higher than maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
vowels = 0;
}
}
// comparing vowels to maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
}
//seek vowels
word = fileIn.next();
for (int i = 0; i < word.length(); i++) {
if
((word.charAt(i) == 'A')
|| (word.charAt(i) == 'E')
|| (word.charAt(i) == 'I')
|| (word.charAt(i) == 'O')
|| (word.charAt(i) == 'U')
|| (word.charAt(i) == 'a')
|| (word.charAt(i) == 'e')
|| (word.charAt(i) == 'i')
|| (word.charAt(i) == 'o')
|| (word.charAt(i) == 'u')) {
//prints the final word with the most consecutive vowels
System.out.println("The word with the most consecutive vowels is: " + word);
System.exit(0);
}
}
}
}
private static boolean hasVowels(char charAt) {
throw new UnsupportedOperationException("Inserted by template."); //NetBeans generated method
}
}
Following the logic, you initialize the String word to null, and then proceed to call word.length().
word, being null, has no length(). Thus, the NullPointerException.
Assign a string to word before attempting to measure its length.
String word = "Hello!";
The variable word seems to be null, I think you skipped an instruction in which you fill it with a word read from fileIn. Your code should read something like this:
while (fileIn.hasNext()) {
// for each word in the file
word = fileIn.next();
int vowels = 0;
for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
...
you defined word as a null. When you say word.length() it means you are saying
null.length() that's why you are getting null pointer exception.
You should initialize String variable "word" before doing any operation( calling any string method by using '.' )
If you have any predefined value, initialize with that else initialize with empty string.
String word = "xyz" ;
String word = "" ;

Taking vowels from string. Java

I'm having trouble with this simple exercise. What I have to do is to take the vowels from the string.
This returns all the vowels in the string, but what I want is that if there are multiple letters of same vowel, just return one.For example, using the string "aaa eee iii" should give "a e i".
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u')) {
aChar = aString.charAt(i);
System.out.print(aChar + " ");
}
}
}
I would recommend either adding each vowel found to a HashSet<Character>, or calling aString.contains() with each vowel in turn. You can also use aString.toLowerCase() so that you only have to check for lowercase vowels.
Edit your code as follows:
public static void getVowels(char aChar, String aString)
{
System.out.print("Your string has the following vowels: ");
String vowels="";
for (int i = 0; i < aString.length(); i++)
{
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u'))
{
if(!vowels.contains(String.valueOf(aString.charAt(i))))
vowels+=aString.charAt(i);
}
}
for(int i=0;i<vowels.length();i++)
System.out.print(vowels.charAt(i)+" ");
}
EDIT :
Alternatively,
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
char vowels[]={'a','e','e','o','u'};
for (char vowel : vowels)
{
if(aString.indexOf(vowel)>=0)
{
System.out.print(vowel+" ");
}
}
}
Why are you doing for loop? Just check String.IndexOf() and if that character is present print it.
You need to have a string where you keep on adding unique vowels checking before hand whether it exists. The below program will clear your doubt.
public class TestWovel {
public static void main(String[] args) {
String vowel = "aaaeeeiiizncnzcxjswdmmnmxcuuooo";
String uniqueVowels = "";
for(int i=0;i<vowel.length();i++){
char vowelFound = vowel.charAt(i);
if((vowelFound == 'a' || vowelFound == 'e' || vowelFound == 'i' || vowelFound == 'o' || vowelFound == 'u') && (uniqueVowels.indexOf(vowelFound) == -1)){
uniqueVowels+=vowelFound;
}
}
System.out.println(uniqueVowels);
}
}
You could use an integer array whose indexes are ASCII codes. When you see a vowel, check its count in the array. If the count is 0, print the vowel and increase the count. For example, 'a' would be stored in arr[97]:
public static void getVowels(String aString) {
int[] arr = new int[128];
char c;
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
if (arr[c] == 0) {
System.out.print(aString.charAt(i) + " ");
arr[c]++;
}
}
}
}

Not sure how to approach english into latin pig java code

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 ";
}
}
}
}

Categories