I have a method that should scan for one of 3 letters in caps or lowercase and return the lower case version of the letter. If an improper letter is entered the user is warned and reasked for a letter. I have two issues, 1: as soon as the method is run I get the outputted line with the error message telling the user invalid entry without waiting for an entry! (so the second the method is run I see High, low or sevens (H/L/S):Invalid entry. Please try again using H/L/S! before entering anything then the method is recalled again and all works fine form there except for my next issue) 2: the entry that is gotten from the scanner never passes any of my if statements even though it should.
my code:
private static char getHighLow(Scanner inScanner) {
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
return 'h';
}
else if (entered.equals("L") || entered.equals("l")){
return 'l';
}
else if(entered.equals("S") || entered.equals("s")){
return 's';
}
char result = 0;
while(result != 'l' || result != 'h' || result != 's'){
System.out.println("Invalid entry. Please try again using H/L/S!");
result=getHighLow(inScanner);
}
return result;
}
Instead of using while(), you can use 'else' like this-
private static char getHighLow(Scanner inScanner) {
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
return 'h';
}
else if (entered.equals("L") || entered.equals("l")){
return 'l';
}
else if(entered.equals("S") || entered.equals("s")){
return 's';
}
else {
System.out.println("Invalid entry. Please try again using H/L/S!");
return getHighLow(inScanner);
}
}
You can simply use equalsIgnoreCase and trim the entered string. And add a while loop util your condition is satisfied.
Scanner scanner = new Scanner(System.in);
boolean loop = true;
String choice = null;
while (loop) {
System.out.print("High, low or sevens (H/L/S):");
choice = scanner.nextLine();
if ("H".equalsIgnoreCase(choice.trim())
|| "L".equalsIgnoreCase(choice.trim())
|| "S".equalsIgnoreCase(choice.trim())) {
System.out.println("Correct Choice");
loop = false;
}
else
{
System.out.println("Wrong Choice");
}
}
System.out.print(choice);
char result;
while(true){
System.out.print("High, low or sevens (H/L/S):");
String entered = inScanner.nextLine();
System.out.print(entered);
if(entered.equals("H") || entered.equals("h")){
result = 'h';break;
}
else if (entered.equals("L") || entered.equals("l")){
result = 'l';break;
}
else if(entered.equals("S") || entered.equals("s")){
result = 's';break;
}else{
System.out.println("Invalid entry. Please try again using H/L/S!");
}
}
Hey you are not breaking out of the while loop at all. Did you see that ?
This is what you want. Here is the program to iterate over characters in a String. And convert them in lower case letter if they are H,L OR S.
package testproj;
import java.util.Scanner;
public class TestProj {
public static void main(String[] args) {
Scanner scanner = new Scanner("HLs");
String result = getHighLow(scanner);
System.out.println("Result :"+result);
}
private static String getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S):");
String entered;
String result = "";
boolean isCharFound = false;
String temp = "";
while (inScanner.hasNext()) {
temp = inScanner.next();
System.out.println(temp);
for (int index = 0; index < temp.length(); index++) {
entered =new Character(temp.charAt(index)).toString() ;
if (entered.equals("H") || entered.equals("h")) {
result = result + 'h';
isCharFound = true;
} else if (entered.equals("L") || entered.equals("l")) {
result = result + 'l';
isCharFound = true;
} else if (entered.equals("S") || entered.equals("s")) {
result = result + 's';
isCharFound = true;
}
if (!isCharFound) {
System.out.println("Invalid entry. Please try again using H/L/S!");
}
isCharFound = false;
}
}
return result;
}
}
Related
I built a Method that would allow me to send a double and return back as a char but the only thing that seems to register is my 'c' return. What am I doing wrong?
public static void playOneGame () {
double max = 100;
double min = 1;
char userInput;
double guess = 50;
userInput = getUserResponseToGuess(guess);
while(userInput !='c') {
if(userInput == 'h') {
min = guess;
guess= midPoint(min,max);
}
else if(userInput== 'l')
{
max = guess;
guess = midPoint(min,max);
}
else {
System.out.println("Input must be (h/l/c)");
userInput = scnr.next().charAt(0);
}
}
while (userInput == 'c')
{
shouldPlayAgain();
public static char getUserResponseToGuess(double guess)
{
char input;
System.out.println("Is it: "+ (int)guess + "(h/l/c)");
input = scnr.next().charAt(0);
return input;
Ok I figured it out and I guess I will answer my own question for anyone who may see this and has a similar question. I initialized the original input but that wont loop back again, so I had to initialize another userInput at the bottom of the loop Ex:
userInput = getUserResponseToGuess(guess);
while(userInput !='c') {
if(userInput == 'h') {
min = guess;
guess= midPoint(min,max);
}
else if(userInput== 'l')
{
max = guess;
guess = midPoint(min,max);
}
else {
System.out.println("Input must be (h/l/c)");
userInput = scnr.next().charAt(0);
}
**userInput = getUserResponseToGuess(guess);**
}
It is right after the else Statement from the initial while loop.
else {
System.out.println("Input must be (h/l/c)");
userInput = scnr.next().charAt(0);
}
**userInput = getUserResponseToGuess(guess);**
}
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
b = scan.next().charAt(0);
if (Character.toString(b).matches("^[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I have this method that checks whether the input is a letter in the alphabet or not, but I want to make sure that the input from the user is not null and that the user only enters one letter. For example "A" or "a" is a correct char, the problem is if I enter "Abcdef" then it is still true as the first letter is still a valid char. I want to make it so that the user can only enter one char, I think I've done that by using the scanner and charAt(0) but is there a more efficient way to do it, and I'm also not sure how to make it so that the input isn't null.
I've revised your code to do what you wanted:
public static boolean correctchar(char b) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
EDIT
Without scanner (see comments):
public static boolean correctchar(char b, String input) {
// This checks if the input is null, is empty (i.e., "") or is bigger than one character
// If any of these conditions are fulfilled, then we return false.
if (input == null || input.length() != 1) {
return false;
}
b = input.charAt(0);
if (Character.toString(b).matches("[a-zA-Z]") ) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
I made couple of changes :
If invalid input ask user to enter again.
Make sure to close the scanner scan.close()
Scanner scan = new Scanner(System.in);
System.out.println("Please enter only one character : ");
String input = scan.next();
while (null == input || input.isEmpty() || input.length() > 1) {
System.out.println("Invaid Input, Please enter only one character : ");
input = scan.next();
}
scan.close();
if (Character.toString(input.charAt(0)).matches("^[a-zA-Z]")) {
System.out.println("True");
return true;
} else {
System.out.println("False");
return false;
}
}
public static boolean correctChar() {
try (Scanner scan = new Scanner(System.in)) {
String input = null;
do {
input = scan.next();
if (input != null && input.length() == 1) {
boolean isCorrect = input.matches("[a-zA-Z]");
System.out.println(isCorrect ? "True" : "False");
return isCorrect;
} else {
System.out.println("Insert only one character");
}
} while (true);
}
}
// I am stuck trying to get my program to only accept a single character from the scanner. Right now the program will accept any amount of characters as long as the first letter is one of the listed letters. I would like to rewrite this code with out the charAt(0) if possible or to add a if statement. if(sea.length > 1){} something like that. I hope I explained the issue well enough to understand. Any help is appreciated, and thank you for your time.
public static char promptForChoice(Scanner in) {
System.out.println("High, Low or Seven(H/L/S");
char sel = in.next().charAt(0);
sel = Character.toUpperCase(sel);
int i = 1;
while (i != 0) {
System.out.println("High, Low or Seven(H/L/S");
if (sel == 'H' || sel == 'L' || sel == 'S') {
i = 0;
} else {
System.out.println("You must enter only H, L or S.");
i = 1;
}
}
return sel;
}
Is there a char.length command?
No, there is no such command. You need to get the input using Scanner::nextLine() and check the length of the input String.
Do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
Scanner in = new Scanner(System.in);
System.out.println(promptForChoice(in));
}
public static char promptForChoice(Scanner in) {
char sel = 0;
String input;
boolean valid;
do {
valid = true;
System.out.print("Enter H/L/S [High/Low/Seven]: ");
try {
input = in.nextLine();
sel = input.toUpperCase().charAt(0);
if (input.length() == 1 && (sel == 'H' || sel == 'L' || sel == 'S')) {
return sel;
} else {
throw new IllegalArgumentException("You must enter only H, L or S.");
}
} catch (IllegalArgumentException e) {
valid = false;
System.out.println(e.getMessage());
}
} while (!valid);
return sel;
}
}
A sample run:
Enter H/L/S [High/Low/Seven]: hello
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: High
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: M
You must enter only H, L or S.
Enter H/L/S [High/Low/Seven]: H
H
Feel free to comment in case of any doubt/issue.
You could get the input from the scanner and put it into a string, then u can do string.length and check it!
the Character length is always 1, I suppose you could achieve what you need with
public static char promptForChoice(Scanner in) {
if(in.next() == "H" || in.next() == "L" || in.next() == "S") {
System.out.println("High, Low or Seven(H/L/S");
return (char) in.next();
}
else {
System.out.println("You must enter only H, L or S.");
// you must always have a return value, in this case
//e.g. the automatically initialized char value
return '\0';
}
}
with your code you could do something like
public static char promptForChoice(Scanner in) {
System.out.println("High, Low or Seven(H/L/S");
char sel = in.next().charAt(0);
if(in.next().length == 1) {
sel = Character.toUpperCase(sel);
int i = 1;
while (i != 0) {
System.out.println("High, Low or Seven(H/L/S");
if (sel == 'H' || sel == 'L' || sel == 'S') {
i = 0;
} else {
System.out.println("You must enter only H, L or S.");
i = 1;
}
}
}
else System.out.println("You must enter only one single character");
return sel;
}
I am coding a JAVA application that translates english to pig latin. My application runs with no actual errors but the output is automatic and incorrect. This application will continue to run if the user selects "y".
Can you all see where my error lies?
Thank you.
CODE:
import java.util.Scanner;
public class PigLatin2 {
public static void main(String[] args) {
// create a Scanner object
Scanner sc = new Scanner(System.in);
// Run through the loop of calculations while user choice is equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.println("Enter a line to be translated");
System.out.println();
//Get String entered
String userInput = sc.toString();
//Line break
System.out.println();
String[] words = userInput.split(" ");
String output = "";
for(int i = 0; i < words.length; i++) {
String pigLatin = translated(words[i]);
output += pigLatin + " ";
}
System.out.println(output);
//Scan next line
sc.nextLine();
//line break
System.out.println();
// Ask use they want to continue
System.out.print("Continue? (y/n): ");
//Users choice
choice = sc.nextLine();
System.out.println();
}//END WHILE LOOP
//Close scanner object
sc.close();
}//END MAIN METHOD
private static String translated(String words) {
String lowerCase = words.toLowerCase();
int firstVowel = -1;
char ch;
// This for loop finds the index of the first vowel in the word
for (int i = 0; i < lowerCase.length(); i++) {
ch = lowerCase.charAt(i);
if (startsWithVowel(ch)) {
firstVowel = i;
break;
}
}
if (firstVowel == 0) {
return lowerCase + "way";
}else {
String one = lowerCase.substring(firstVowel);
String two = lowerCase.substring(0, firstVowel);
return one + two + "ay";
}
}
public static Boolean startsWithVowel(char ch) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y') {
return true;
}
return false;
}
}
This is the output I get automatically:
ava.util.scanner[delimiters=\p{javawhitespace}+][position=0][matchjay alid=false][needvay input=false][sourceway osed=false][skipped=false][groupclay eparator=\,][decimalsay eparator=.][positivesay efix=][negativepray efix=\q-\e][positivepray uffix=][negativesay uffix=][nansay ing=\qnan\e][infinitystray ing=\q?\e]stray
For some reason, with this code, tests that I've run shows that the program entirely skips the nextLine request for an input from the user and it registers as blank space for its first iteration. Afterwards it'll go back to the beginning of the while loop and take an input, but no matter what I type in it (whether it's y or Y for yes, N or n for no) it'll go to the else statement. I don't understand what I'm doing wrong, help!
private static boolean promptForPlayAgain(Scanner inScanner) {
boolean play = true;
int test = 0;
while(test == 0)
{
System.out.println("Would you like to play again [Y/N]?:");
String input = inScanner.nextLine();
System.out.println(input);
if (input == "y" || input == "Y")
{
test++;
}
else if (input == "n" || input == "N")
{
play = false;
test++;
}
else
{
System.out.println("ERROR! Only 'Y' or 'N' allowed as input!");
}
}
return play;
}
With the tips from what you guys said I've edited and ran my code which now works. Thanks a lot guys!
private static boolean promptForPlayAgain(Scanner inScanner) {
boolean play = true;
int test = 0;
while(test == 0)
{
System.out.println("Would you like to play again [Y/N]?:");
inScanner.nextLine();
String input = inScanner.nextLine();
if (input.equals("y") || input.equals("Y") )
{
test++;
}
else if (input.equals("n") || input.equals("N") )
{
play = false;
test++;
}
else
{
System.out.println("ERROR! Only 'Y' or 'N' allowed as input!");
}
}
return play;
}