How do i reprompt invalid user input and restore the value? - java

Can anyone explain why the while loop ask whatNight twice? and how to reprompt invalid user input if user input something other than 'r' or 'c'
for(int x = 1; x <= inputInt; x++) {
char whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0);
boolean pleasework = whatNight == 'c' || whatNight == 'C';
boolean imbeggingu = whatNight == 'r' || whatNight == 'R';
boolean doesNotWork = whatNight != 'c' && whatNight != 'C' && whatNight != 'r' && whatNight != 'R';
//why does the while loop ask twice even if u enter c or r?
while(pleasework || imbeggingu || doesNotWork) {
if(doesNotWork)
JOptionPane.showMessageDialog(null, "INvalid letter");
whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0);
//reprompt not storing in whatNight variable :/
if(pleasework)
JOptionPane.showMessageDialog(null, "You entered c for carnight");
else if(imbeggingu)
JOptionPane.showMessageDialog(null, "You entered r for regular night");
break;
}

To answer your question I would recommend you to debug your values as a first step e.g
System.out.println(pleasework);
Your concepts logic is pretty off aswell and you should rethink how you want to handle the issue. For example when your input is not C or R you ask for a new input but you dont set any boolean according to it.
this should work!
for(int x = 1; x <= inputInt; x++) {
char whatNight = JOptionPane.showInputDialog("Enter c or r for what type of night").charAt(0);
whatNight = checkInput(whatNight);
boolean nightC = whatNight == 'c' || whatNight == 'C';
boolean nightR = whatNight == 'r' || whatNight == 'R';
if(nightC) {
JOptionPane.showMessageDialog(null, "You entered c for carnight");
} else if(nightR) {
JOptionPane.showMessageDialog(null, "You entered r for regular night");
}
}
---------------------------------------------------------------------
private char checkInput(char input) {
if(input == 'c' || input == 'C' || input == 'r' || input == 'R') {
return input;
}
char whatNight = JOptionPane.showInputDialog("You entered a wrong letter, enter either c or r for what type of night it was").charAt(0);
return checkInput(whatNight);
}
If you dont understand something let me know and I'll explain!

Related

Rules not obeyed by if statement

The below code is supposed to tell the user whether his input is a vowel or consonant or digit less than 1. The program however returns "Vowel" for all capital letters including consonants and whenever a digit is entered "Consonant" is returned. Ex - if a is entered, result = vowel. If b, result = Consonant. If B, result = Vowel (should be Consonant). If 1, result = Consonant(should be Digit) . Any advice would be greatly appreciated. Thanks.
package checkVowelorConstantorNumber;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
boolean tf = false;
while(tf == false) {
System.out.println("Enter a character which is a - z or A - Z or
less than 1");
char cha = inp.next().charAt(0);
inp.nextLine();
if(Character.isLetter(cha) && cha == 'a'||cha == 'e' || cha == 'i' || cha == 'o' || cha == 'u' || Character.isUpperCase(cha)) {
System.out.println("Vowel");
}
else if(Character.isLetter(cha) && cha != 'a'|| cha != 'e' || cha != 'i' || cha != 'o' || cha != 'u' || Character.isUpperCase(cha)) {
System.out.println("Consonant");
}
else if(Character.isDigit(cha) && cha <= 1 ) {
System.out.println("Digit");
}
else System.out.println("Invalid character");
}
}
}
Your if statement first checks if the given character is a letter and not an a, 1 is neither so that is false, then it checks if 1 is not equal to 'e' causing that statement to be true, thus printing 'Consonant'. You have to make the check for isLetter for every comparison. Therefore i would recommend something like this:
if(Character.isLetter(cha)) {
// Check for vowel or consonant based on letters
} else if(Character.isDigit(cha) && cha <= '1') {
System.out.println("Digit");
} else {
System.out.println("Invalid character");
}
You also should make the if statement for consonant use && instead of ||, since it should be none of the specified chars.
Pay close attention to logical ands (&&), logical ors (||) and parentheses. Consider the following, modified from your code with some comments.
char cha = inp.next().charAt(0);
inp.nextLine();
if (cha.isLetter()) {
// convert to uppercase to simplify the if
char uc = cha.toUpperCase();
if (uc == 'A' || uc == 'E' || uc == 'I' || uc == 'O' || uc == 'U') {
// it's a vowel
} else {
// it's a letter that isn't a vowel (consonant)
}
} else {
// it's not a letter
if (cha.isDigit() && cha < '1') {
// but it is a digit less than 1
} else {
// it's something else (digit not less than '1' or not a digit)
}
}

Trying to end loop when user input = q

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

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

Why does the do/while loop keep adding the input each time the switch statement fires?

Write a class with a constructor that accepts a String object as its argument. The class should have a method that
returns the number of vowels in the string, and another method that returns the number of consonants in the string.
Demonstrate the class in a program that performs the following steps:
The user is asked to enter a string.
The program displays the following menu:
a: Count the number of vowels in the string
b: Count the number of consonants in the string
c: Count both the vowels and consonants in the string
d: Enter another string
e: Exit the program.
The program performs the operation selected by the user and repeats until the user selects e, to exit the program.
When the user enters a string and checks for consonants, or vowels, or both once, it works just fine.
But when it is passed again, the program doubles the value.
Thoughts?
Class:
public class CounterClass
{
String string;
int vow = 0;
int con = 0;
char letter = ' ';
int enter = 0;
/**
* This is a Constructor
* It accepts a string object.
*/
public CounterClass(String aString)
{
this.string = aString;
}
/* #returns an int
* This method checks for char and then adds it to a vowel counter */
public int getVowels(String aString)
{
int length = aString.length();
for( int i = 0; i < length ; i++)
{
char c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i'|| c == 'o'
|| c == 'u' ||c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U')
{
vow++;
}
}
return vow;
}
/* #returns an int
* This method checks for char and then adds it to a con counter */
public int getConsonants(String aString)
{
int length = aString.length();
for( int i = 0; i < length ; i++)
{
char c = aString.charAt(i);
if (c == 'B' || c == 'C' || c == 'D'|| c == 'F'
|| c == 'G' ||c == 'H' || c == 'J' || c == 'K'
|| c == 'L' || c == 'M'|| c == 'N' || c == 'P'|| c == 'Q'
|| c == 'R' ||c == 'S' || c == 'T' || c == 'V'
|| c == 'W' || c == 'X'|| c == 'Z' || c == 'b' || c == 'c' || c == 'd'|| c == 'f'
|| c == 'g' ||c == 'h' || c == 'j' || c == 'k'
|| c == 'l' || c == 'm'|| c == 'n' || c == 'p'|| c == 'q'
|| c == 'r' ||c == 's' || c == 't' || c == 'v'
|| c == 'w' || c == 'x'|| c == 'z')
{
con++;
}
}
return con;
}
}
Main Program :
import javax.swing.JOptionPane;
public class NumberCounters
{
public static void main(String [] args)
{
//Declaring variable for later use.
String input = " ";
String letters = " ";
char letter = ' ';
StringBuilder sb = new StringBuilder();
//This creates an instance of CounterClass
CounterClass string = new CounterClass(input);
//Tests
System.out.println(string.getVowels(input));
System.out.println(string.getConsonants(input));
input = JOptionPane.showInputDialog("Please enter a string"); // Getting a string input from the user.
//Does a loop until the user selects 'e'
do{
//sets 'letters' to the inputdialog from the menu
letters = JOptionPane.showInputDialog(
"a: Count the number of vowels in the string\n" +
"b: Count the number of consonants in the string\n" +
"c: Count both the vowels and consonants in the string\n"+
"d: Enter another string\n" + "e: Exit the program");
letter = letters.charAt(0); // letters is a string so I used charAt to grab the first letter from the input.
switch(letter)
{
case 'A':
case 'a': JOptionPane.showMessageDialog(null, "You have " + string.getVowels(input) + " vowels in your string");
break;
case 'B':
case 'b': JOptionPane.showMessageDialog(null, "You have " + string.getConsonants(input) +
" consonants in your string");
break;
case 'C':
case 'c': JOptionPane.showInputDialog(null, "You have " + string.getConsonants(input)
+ " Consonants and " + string.getVowels(input)
+ " vowels in your string");
break;
case 'D':
case 'd': input = JOptionPane.showInputDialog("Please enter a string");
break;
case 'E':
case 'e':
System.exit(0);
}
}while( letter != 'e');
}
}
try setting your values back to 0 in each method you could also remove the getConsonants method and just place an else(example of edited code below)
public int getVowels(String aString)
{
//set values to back to 0 before checking
vow = 0;
con = 0;
int length = aString.length();
for( int i = 0; i < length ; i++)
{
char c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i'|| c == 'o'
|| c == 'u' ||c == 'A' || c == 'E' || c == 'I'
|| c == 'O' || c == 'U')
{
vow++;
}
else if(c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9' || c == '0' ||){
//in case you add numbers put here
}
else
{
con++;
}
}
return vow;

Categories