I am trying to catch no input (enter key) and invalid input everything but y/n in one method. I tried it two different ways (pasted) but I cannot make work both “enter key” and “mistype y/n” together. Thank you for your help.
1st attempt:
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid){System.out.print("Continue? (y/n): ");
if (sc.hasNext()){
choice = sc.next();
isValid = true;
} else {System.out.println("Error! "
+ "This entry is required. Try again");
}
if (isValid && !choice.equals("y") || !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
2nd attempt
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice;
while (true) {choice = sc.next();
//?????????????????????????????????????????????????????
if (choice.length() == 0){ System.out.println("Error! "
+ "This entry is required. Try again");
continue;
}
if (!(choice.equals("y") || choice.equals("n"))) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
continue;
}
break;
}
sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
I tried with 1st attempt of your code. I explained with comment line which is included in below code like ;
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Continue? (y/n): ");
choice = sc.nextLine(); //to reads all line , because this cannot read with empty enter input
isValid = true;
if (choice.isEmpty()) { //this isEmpty for empty enter
System.out.println("Error! "
+ "This entry is required. Try again");
}
System.out.println(choice);
//this logic if not y or n , it will return error
if (!choice.equals("y") && !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
Your if statement in first case is wrong. You are checking if choice is not equal to 'y' or not equal to 'n' which will always be true .
Change
if (isValid && !choice.equals("y") || !choice.equals("n"))
To
if (isValid && !choice.equals("y") && !choice.equals("n"))
Related
I’m trying to validate inputs from the user. The user needs to enter (y + press enter) many times. If the user presses enter without (y), is there a way to validate the enter key?
public static void getInput() {
Scanner input = new Scanner(System.in);
System.out.print("Press 'y' to continue, 'n' to exit: ");
char c = input.nextLine().charAt(0);
if (c == 'n') {
System.out.println("Exiting");
System.exit(0);
}
while (c != 'y') {
System.out.println("Invalid input!");
System.out.println("Press 'y' to continue, 'n' to exit: ");
c = input.nextLine().charAt(0);
}
if (c == 'n') {
System.out.println("Exiting");
System.exit(0);
}
}
Just check if the input line is empty:
String line = input.nextLine()
if(line.isEmpty())
//handle no input
This might help.
Scanner input = new Scanner(System.in);
while(true){
System.out.print("Press 'y' to continue, 'n' to exit: ");
char c = input.nextLine().charAt(0);
if(c == 'n'){
System.out.println("Exiting...");
break;
}
else if(c == 'y'){
//call your method here
//method();
System.out.println("User has input Y");
break;
}
else{
System.out.println("Please enter a valid keyword");
}
}
Or you can use a switch case.
I am trying to learn try-catch uses and have to validate input so that the user must enter 1 or 2 for the program to continue. I believe I am close, but cannot seem to get the program to continue if the user enters something wrong such as '3' or '2.12'.
Here's what I have:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
I don't necessarily see the point of using InputMismatchException for your use case. Instead, if the input doesn't match what you expect, you can log an error and just prompt the user to input again.
But [Integer#parseInt()][1] can throw an exception if the input isn't an actual integer. In your original code you never actually use the result of this call, but I have done so in my answer. In this case, it does potentially make sense to use a try-catch block.
int result;
while (true) {
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
result = Integer.parseInt(input);
} catch(Exception e) {
System.out.println("Could not parse input, please try again.");
continue;
}
if (result != 1 && result != 2) {
System.out.println("Invalid input! Please select '1' or '2':");
}
else {
break;
}
}
You should put in your condition the throw statement in able to your catch statement fetch the error, the code should be like this:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
throw new InputMismatchException ();
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
The code is expecting for positive integers but can input string and loop again until got a positive integer input value.
Scanner scanner = new Scanner(System.in);
Integer expectedOutput = -1;
public Integer getInputNumber(){
boolean valid;
String inputData;
do {
System.out.print("Enter Input Number: \t");
try {
inputData = scanner.nextLine();
// expecting positive integers
if (Integer.parseInt(inputData) > 0) {
expectedOutput = Integer.parseInt(inputData);
valid = true;
} else {
System.out.println("Invalid Input!");
valid = false;
}
} catch (Exception ex){
valid = false;
}
} while(!valid);
return expectedOutput;}
I really do not know to how explain this but here we go.
I am testing something for a bigger program I have to make. In the program I have to validate input from the user to see if it is being to be accepted as a valid answer.
I have the code to where it will say if the input is invalid but if I attempted to enter another letter the code crashes with this error:
Enter a letter:
f
Your answer is not valid.
A
Enter a letter:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at example.main(example.java:18)
Here is the code:
import java.util.Scanner;
public class example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
user_answer=input.nextLine().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
input.next();
}
}
while (!UserInput);
}
}
either remove input.next() or change it to input.nextLine()
What's happening is that input.next() will catch the A you input. Then you go back to the beginning of the do and start over, and do input.nextLine() but you had already pressed enter to input A and the A was consumed by input.next().
Remove the input.next(); and it will work fine. The reason is because when you use input.next(), it reads the next character the user types, without exiting the line. Then when the input.nextLine() executes, it reads that same line, but immediately after the number. Since nothing is after the number, it reads in nothing "" and the charAt(0); becomes out of bounds.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean UserInput;
do
{
char user_answer = 0;
System.out.println("Enter a letter:");
// user_answer=input.nextLine().charAt(0);
user_answer=input.next().charAt(0);
if ( user_answer == 'A')
{
UserInput = true;
}
else if (user_answer == 'B')
{
UserInput = true;
}
else if (user_answer == 'C')
{
UserInput = true;
}
else if (user_answer == 'D')
{
UserInput = true;
}
else
{
System.out.println("Your answer is not valid.");
UserInput = false;
// input.next();
}
}
while(!UserInput);
}
}
This should be a program to take in a password from the user and check it against various parameters.
I've an issue with the do while loop, it prints:
Please enter your password.
Error. Password is too short. Try again.
Then it prints this after selecting option
1. Enter your own password for verification
The program should allow the user to enter a password before printing any error messages.
First time using this site. Any help with this would be greatly appreciated.
import java.security.SecureRandom;
import java.util.*;
public class CC_CA2
{
// Main Method
public static void main(String[] args)
{
Scanner keyboardIn = new Scanner(System.in); //Create Scanner object
String[] data = {"123456","password","12345","12345678","qwerty","123456789","1234","baseball","dragon","football","1234567","monkey","letmein","abc123","111111","mustang","access","shadow","master","michael"};
String correct;
int numLetterCheck = 0;
int option;
boolean found = false;
boolean check;
boolean digitFound = false;
boolean letterFound = false;
//Menu
System.out.println("Welcome to the password checker.");
System.out.println("Would you like to:");
System.out.println("1. Enter your own password for verification.");
System.out.println("2. Have an easy to remember random password generated for you.");
option = keyboardIn.nextInt();
if (option==1)
{
do
{
check = true;
found=false;
System.out.println("Please enter your password."); // get user password
correct = keyboardIn.nextLine();
if (correct.length()<8) // 1. check password > 8 characters
{
System.out.println("Error. Password is too short. Try again.");
check=false;
continue;
}
if (correct.contains(" ")) //2. check if password contains any spaces
{
System.out.println("Error. Password contains a space. Try again.");
check=false;
continue;
}
for(int i = 0; i < data.length; i++) // 3. check common passwords
{
if(data[i].equals(correct)) //if match found
{
found = true; //remember that it is found
}
}
if(found) //if found is true
{
System.out.println("Error. This is a common password. Try again.");
check=false;
continue;
}
for (char ch : correct.toCharArray()) // 4. Make sure password contains at least one letter and one number
{
if (Character.isDigit(ch))
{
digitFound = true;
}
if (Character.isLetter(ch))
{
letterFound = true;
}
if (digitFound && letterFound)
{
numLetterCheck = 0;
}
else
{
numLetterCheck = 1;
}
}
while (numLetterCheck == 1)
{
letterFound=false;
digitFound=false;
System.out.println("Error. Password must contain at least one letter and one number. Try again.");
correct = keyboardIn.nextLine();
}
}while(check == false);
}
}}
I'm wondering why when I type 'y' after being asked if there are any more digits in this method the code works correctly and leaves the loop, but upon typing 'n' and hitting return, I need to type 'n' and hit return again or the process just hangs.
Why?
The string 'input' is being passed from the user's input in the main method and is in this case "addition".
private int add(String input)
{
int additionValue = 0;
boolean keepGoing = true;
if (input.matches("addition"))
{
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
if (scan.next().matches("Y|y"))
{
keepGoing = true;
}
else if (scan.next().matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
}
}
I've managed to get the code working by using
System.out.println("Any more digits? Type y/n");
String yayOrNay = scan.next();
if (yayOrNay.length()==1 && yayOrNay.charAt(0)=='y')
{
keepGoing = true;
}
but that seems a little too complicated to me for all that it's doing.
scan.next() pulls a new character from the input steam.
So when you check for 'n' and scan.next().matches("Y|y") executes, it is actually skipping 'n' for your next comparison.
The solution is to assign scan.next() into a variable you can use:
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
String next = scan.next();
if (next.matches("Y|y"))
{
keepGoing = true;
}
else if (next.matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
This is because you call scan.next() two times.
You have to call it one time, putting the resulting string in a variable.
String input2 = scan.next();
if (input2.matches("Y|y"))
{
keepGoing = true;
}
else if (input2.matches("N|n"))
{
keepGoing = false;
}
You need to enter 'n' twice because you scan for input in each if condition. So if the letter is not a 'y', your program will wait for user input in the next if statement.
You can simply do:
String yayOrNay = scan.next();
if (yayOrNay.matches("Y|y"))
{
keepGoing = true;
}
else if (yayOrNay.matches("N|n"))
{
keepGoing = false;
}
...
if (scan.next().matches("Y|y"))
{
keepGoing = true;
}
else if (scan.next().matches("N|n"))
You call scan.next twice
1st time you check if its Y, if it isn't you read from input again
so
somevar=scan.next()
if (somevar.matches("Y|y"))
{
keepGoing = true;
}
else if (somevar.matches("N|n"))
{
keepGoing = false;
}
else ..
Your error is to call scan.next() twice, which requests two imputs.
private int add(String input)
{
int additionValue = 0;
boolean keepGoing = true;
if (input.matches("addition"))
{
while (keepGoing == true)
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
System.out.println("Any more digits? Type y/n");
String s = scan.next();
if (s.matches("Y|y"))
{
keepGoing = true;
}
else if (s.matches("N|n"))
{
keepGoing = false;
}
else
{
System.out.println("Great, you broke it.");
System.exit(1);
}
}
}
}
Please Try This,
Scanner scan = new Scanner(System.in);
int additionValue=0;
while (true)
{
System.out.println("Any more digits? Type y/n");
if (scan.next().matches("Y|y"))
{
System.out.println("Next digit = (Type the digit)");
additionValue = additionValue + scan.nextInt();
//System.out.println("Any more digits? Type y/n");
}
else
{
System.out.println("Thanks");
break;
}
}
I am not sure whether this logic will work for you. 'If you want you can process 'n' also'
output
Any more digits? Type y/n
y
Next digit = (Type the digit)
5
Any more digits? Type y/n
n
Thanks