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 ";
}
}
}
}
Related
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);
}
}
Essentially I am trying to create a Pig Latin converter. However, for this assignment a requirement is to allow the user to enter 'Q' to quit entering in words. I can get the code to compile, but whenever the user enters Q it crashes and throws:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at mission4aa.Mission4AA.main(Mission4AA.java:38)
I am just completley unsure where to even go about fixing this. I've been trying.
import java.util.Scanner;
public class Mission4AA {
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
System.out.println("Enter another word(Q to exit): ");
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}
}
Because when you are doing this check
if(userInput.charAt(1) != firstVowel) {
If the user has input a 'q', userInput will only have a 0 term ( Length 1 ). You are effectively trying to get the second character of the users input. To solve your problem, i would do the check for 'q' at the start of the do section ( or simply scrap the do-while concept and use a while(true) loop ). Note that in future you should handle input that is of length 1. But for your issue, something like this would work
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
//here
if(userInput.equals("q") || userInput.equals("Q")){
System.out.println("Thank you");
return;
}
//else continue
If the user enters just Q or q - there's no char at index 1, which is why your code throws the java.lang.StringIndexOutOfBoundsException exception.
There are many ways to fix this. In my case, I just converted your do-while to a while(true) and I use break if the input is just Q or q.
// get first input
userInput = scanIn.next();
while(true){
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
// check next word here - if Q or q, break out and finish
userInput = scanIn.next();
if(userInput.equalsIgnoreCase("q")) {
break;
}
System.out.println("Enter another word(Q to exit): ");
}
Note - you'd need to rearrange your print statements accordingly.
The problem appears to be that you read the user input in the beginning of the loop, thus the condition in your do-while loop checks the previous user input - not the new one.
In addition the else-branch of your if-statement assumes that the input is at least 2 characters long if(userInput.charAt(1) != firstVowel) {...}.
This is what causes the exception as the input "q" reaches the else-branch, but is only of length 1.
You need to make two changes to your code:
You need to read the userinput before checking the loop-condition.
In the else-branch you must check that the input is at least 2 characters long before checking if the second character is a vowel.
Modified code below:
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
do {
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(end > 1 && userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
} else { /* Handle handle input of length 1 */}
}
System.out.println("Enter another word(Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}
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())
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 = "" ;
I am writing this program that calculates the Flesch index of a passage in Java. A few things: I can't figure out how to make it to where you can input as many words as you like while hitting enter and it will not calculate (something like d tells it that no more input is coming). I am also having trouble with this boolean expression. I have tried & and && and it still doesn't work. I keep getting a message that says, "Syntax error on token "&&", throw expected"
import java.util.Scanner;
public class Flesch
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
// Declare variables for syllables and words
int totalWords = 0;
int totalSyllables = 0;
// Prompt user for a passage of text
System.out.println ("Please enter some text:");
String passage = input.nextLine();
// Words
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == ' ') {
totalWords++;
}
else if (passage.charAt(i) == '.') {
totalWords++;
}
else if (passage.charAt(i) == ':') {
totalWords++;
}
else if (passage.charAt(i) == ';') {
totalWords++;
}
else if (passage.charAt(i) == '?') {
totalWords++;
}
else if (passage.charAt(i) == '!') {
totalWords++;
}
else {
totalWords = totalWords;
}
}
System.out.println ("There are " + totalWords + " words.");
char syllableList [] = {'a', 'e', 'i', 'o', 'u', 'y'};
// Syllables
for (int k = 0; k < syllableList.length; k++)
{
for (int i = 0; i < passage.length(); i++)
{
if (passage.charAt(i) == syllableList[k]) && (passage.charAt(i) == syllableList[k]); {
totalSyllables = totalSyllables;
}
if (passage.charAt(i) == syllableList[1] + ' ') {
totalSyllables = totalSyllables;
}
if (passage.charAt(i) == syllableList[k]) {
totalSyllables++;
} else {
totalSyllables = totalSyllables;
}
}
}
System.out.println ("There are " + totalSyllables + " syllables.");
}
}
I know I will have to type in the calculations, but right now I was just trying to get it to count the number of words and syllables. Once this works, I will add in the calculation to find the Flesch index. Thanks for the help guys. For some reason I get an error on the line that says
if (passage.charAt(i) == syllableList[k]) && (passage.charAt(i) == syllableList[k]);
And I have no clue why I am getting this or how to fix it.