Trying to end loop when user input = q - java

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

Related

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, The loop doesn't start over from the beginning of the program [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
I am just finishing my program, but I still have one problem left that I can't seem to find an answer too. I have been looking through already asked questions but I couldn't find something that specifically answers my question in this case. This is a program that lets the user input a string and then it counts how many vowels and consonants etc. And after this the user gets an option to repeat the program and input a new string if he/she press y, the program quits if he/she press n etc. The only thing that is not working is if the user presses y to repeat the program, it then prints out that there are 0 vowels and consonants etc. I know that it is something in the beginning of my code where I have int consonant_count=0 for example, I just can't figure out what to move and where to move it. Ps. this shouldn't be flagged as a duplicate since I didn't know that nextLine was the problem. Here is the code:
import java.util.Scanner;
public class loop2
{
public static void main (String[] args)
{
Scanner inputReader = new Scanner (System.in);
char result='y';
do {
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++)
{
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' || chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
// Kod f ̈or hantering av repetition
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.next();// H ̈amta anv ̈andarens svar.
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
result='y';
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
}
while (result == 'y'); // Observera semikolon!
}
}
You should use the nextLine() when reading input from the user, this grabs everything including the end of line character '\n' which is what gets left over after your next() call and then nextLine() grabs the '\n' which gives you the counts of 0, 0 for vowels and consonents
Scanner inputReader = new Scanner (System.in);
char result='y';
while(result == 'y')
{
// ’Nytto’-kod:
int vowels_count = 0;
int consonents_count = 0;
int charachters_count= 0;
System.out.println("Skriv in en text");
String str = inputReader.nextLine();
String str2 = str.toLowerCase();
char[] chr = str2.toCharArray();
for(int i=0;i<chr.length;i++)
{
if(chr[i] == 'a' || chr[i]== 'e' || chr[i] == 'i' || chr[i] == 'o' || chr[i] == 'u')
vowels_count++;
else if(chr[i] == '-' || chr[i] == '!' || chr[i] == '?' || chr[i] == ',' || chr[i] == '.' || chr[i] == ':' || chr[i] == ';')
charachters_count++;
else
consonents_count++;
}
System.out.println("Antalet vokaler:"+vowels_count+ " "+"Antalet konsonanter:"+consonents_count+" "+"Antalet interpunktionstecken:"+charachters_count++);
//wrap your play again logic in another do/while where you
// ask for y or n until they enter either one
do {
System.out.println ("För att upprepa: Skriv y");
System.out.println ("För att avsluta: Skriv n");
String repeat=inputReader.nextLine();//read the entire next line <----
result=repeat.charAt(0);
if(result=='y')
{
continue;
}
else if(result !='y' && result !='n')
{
System.out.println("Du får bara skriva y eller n, försök igen!");
}
else
{
System.out.println ("Klart.");
inputReader.close ();
}
} while (result !='y' && result !='n');
}

Keep Prompting Input From User

I have an assignment to do. I need to convert alphabets to telephone numbers. Add hyphen after the 3rd number and after every subsequent 4 numbers. Then I need to allow user to keep on entering input.
I've already gotten 3/4 of my codes done. It's not working. I'm only stuck with the part to keep prompting user for input.
This is my java code so far. Please help me and tell me what's wrong with my code. I'm new to Java, please be nice. Thank you!
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Enter letters: ");
String phonenumber = input.next();
String phone = phonenumber.replaceAll("\\s", " ");
int count = 0;
int prevCount = 0;
while (!phone.equals("#")){
for (int i = 0; i < phone.length(); i++)
{
char letter = Character.toLowerCase(phone.charAt(i));
if (letter == 'a' || letter == 'b' || letter == 'c')
{
System.out.print(2);
count++;
}
if (letter == 'd' || letter == 'e' || letter == 'f')
{
System.out.print(3);
count++;
}
if (letter == 'g' || letter == 'h' || letter == 'i')
{
System.out.print(4);
count++;
}
if (letter == 'j' || letter == 'k' || letter == 'l')
{
System.out.print(5);
count++;
}
if (letter == 'm' || letter == 'n' || letter == 'o')
{
System.out.print(6);
count++;
}
if (letter == 'p' || letter == 'q' || letter == 'r' || letter == 's')
{
System.out.print(7);
count++;
}
if (letter == 't' || letter == 'u' || letter == 'v')
{
System.out.print(8);
count++;
}
if (letter == 'w' || letter == 'x' || letter == 'y' || letter == 'z')
{
System.out.print(9);
count++;
}
if (count == 3 || count - prevCount == 4)
{
System.out.print('-');
prevCount = count;
}
}
System.out.println();
System.out.println("Enter letters: ");
input.nextLine();
}
}
use a loop:
while (true)
{
System.out.println("Enter letters: ");
String phonenumber = input.next();
if something break;
or
while ((String phonenumber = input.next())!=null)
{
// ...
System.out.println("Enter letters: ");
}
Your problem is here :
System.out.println();
System.out.println("Enter letters: ");
input.nextLine(); // you forgot to assign the String returned by nextLine
// into your phone variable
Beside that, you should reset your counters in each iteration of the while loop.
while (!phone.equals("#")) {
int count = 0;
int prevCount = 0;
... your for loop ...
System.out.println();
System.out.println("Enter letters: ");
phone = input.nextLine();
}

Java count the vowels program [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to make a program that lets the user input a word, then it will count the number of vowels and consonants in that word and print the amount. e.g: The word 'YOURWORD' contains 3 vowels and 5 consonants.
Since a consonant is just each letter that isn't a vowel, I only made the program check if there was a vowel in the word and then the number of consonants is just the number of other letters in the word. However, I'm struggling with the for loop. Here is my code:
String word;
Scanner myinput = new Scanner(System.in);
System.out.println("Please enter a word.");
word = myinput.next();
char[] wordc = word.toCharArray();
for(int w = 0;w > word.length();w++;) {
if(wordc[w] == 'a' || wordc[w] == 'e' || wordc[w] == 'i' || wordc[w] == 'o' || wordc[w] == 'u') {
}
As you can see, I'm so close to the end but I literally have no clue what to do now. I'm a beginner at Java and I have checked the for loop syntax but I really don't know what to do, please help.
Try changing
for(int w = 0;w > word.length();w++)
to
for(int w = 0;w < word.length();w++)
because when you set w to 0, obviously, your word.length() is greater than 0, which makes the condition in the for loop false. Hence, the for loop would be not be executed even once.
To count the number of vowels, you define one more integer outside the for loop and increment it as you encounter a vowel. So, your code should look like:
String word;
Scanner myinput = new Scanner(System.in);
System.out.println("Please enter a word.");
word = myinput.next();
//Convert your string to lowercase using toLowerCase() method.
char[] wordc = word.toLowerCase().toCharArray();
int vowels = 0; //This counter will count the vowels.
for(int w = 0;w < word.length();w++) {
if(wordc[w] == 'a' || wordc[w] == 'e' || wordc[w] == 'i' || wordc[w] == 'o' || wordc[w] == 'u') {
vowels++;
}
}
int consonants = word.length() - vowels;
//Assuming no special characters in your word.
You should define two int variables to do counting.
the for loop goes like below
String word;
int numberOfVowls = 0; numberofCosonents = 0;
Scanner myinput = new Scanner(System.in);
System.out.println("Please enter a word.");
word = myinput.next();
char[] wordc = word.toCharArray();
for(int w = 0;w < word.length();w++;) {
if(wordc[w] == 'a' || wordc[w] == 'e' || wordc[w] == 'i' || wordc[w] == 'o' || wordc[w] == 'u') numberOfVowls++;
else numberofCosonents++;}
String word;
Scanner myinput = new Scanner(System.in);
System.out.println("Please enter a word.");
word = myinput.next();
char[] wordc = word.toCharArray();
int vowels = 0;
for (char w: wordc) {
if(w == 'a' || w == 'e' || w == 'i' || w == 'o' || w == 'u') {
vowels++;
}
}
System.out.println("Number of vowels in " + word + " is: " + vowels);
System.out.println("Number of consonants in " + word + " is: " + (wordc.length - vowels));
Here is a way to count vowels and consonants without using loops and multiple conditions.
String word = "YOURWORD"; // assuming only letters
String vowels = word.replaceAll( "(?i)[^aeiou]+", "" ); // OUO
int numVowels = vowels.length(); // 3
int numConsonants = word.length() - numVowels; // 5
How it works:
In the word.replaceAll( "(?i)[^aeiou]+", "" ) call we are replacing everything that is not one of [^aeiou] thus leaving only vowels in returned string.
String[] arr = text.split(" ");
char elementch = ' ';
//looping through string array
for(int i=1; i<= arr.length ; i++){
String nextElement = arr[i-1];
int add = 0;
//looping through each character in the next element
for (char ch: nextElement.toCharArray()) {
//checking if ch == to vowels
if(ch == 'e'|| ch == 'a' || ch == 'o' || ch == 'u'|| ch == 'i'){
//add counts number of vowels for every string array index
add = add +1;
elementch = ch;
System.out.print(" ' " +elementch + " ' ");
}else{
//do nothing
}
}
System.out.println("The number of vowels is "+ add + " in" + " : " + nextElement.toUpperCase());
}

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