Is there a way to validate the enter key? - java

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.

Related

How do I fix my loops from taking the enter key as input.in Java?

This question is similar to a question I had previously about loops taking my enter key as input. For my class, I need to write a program that is a number-guessing game that whenever the user enters correctly, the loop ends. But I run into the problem as the enter key being taken as input. How can I stop this from occurring? Here is my code I have so far.
String secretNumber = "6";
String guess = "";
while(!guess.equals(secretNumber)) {
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
if(guess == "6") {
System.out.println("You Win!");
}
else if(guess == "5") {
System.out.println("Try again!");
}
else if(guess == "4") {
System.out.println("Try again!");
}
else if(guess == "3") {
System.out.println("Try again!");
}
else if(guess == "2") {
System.out.println("Try again!");
}
else if(guess == "1") {
System.out.println("Try again!");
}
else if(guess == "7") {
System.out.println("Try again!");
}
else if(guess == "8") {
System.out.println("Try again!");
}
else if(guess == "9") {
System.out.println("Try again!");
}
else if(guess == "10") {
System.out.println("Try again!");
}
else {
System.out.println("You did not enter a number between 1 and 10");
}
}
}
}
If you use == operator it doesn't compare the value of the string. So to check if a string's value equals to another, you must use string.equals(anotherString) method. In your case your code should be like :
String secretNumber = "6";
String guess = "";
while(!guess.equals(secretNumber)) {
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
if(guess.equals("6")) {
System.out.println("You Win!");
}
else if(guess.equals("5")) {
System.out.println("Try again!");
}
..........
Also to refactor the code this version is more readable and simpler.
String secretNumber = "6";
String guess = guess = scan.next();
System.out.println("Guess a number between 1 and 10");
while(!guess.equals(secretNumber)) {
if(guess.equals(secretNumber)) {
System.out.println("You Win!");
break;
}
else{
System.out.println("Try again!");
}
First Strings are compared by equals second you need to learn how to reduce your code because while(!guess.equals(secretNumber)) will continue until 6 is entered so it will print anything inside it you we just print Try Again
public class GuessIt{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String secretNumber = "6";
String guess = "";
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
while(!guess.equals(secretNumber)) {
System.out.println("Try again");
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
}
System.out.println("You guessed it");
}
}
While your code is not the best way to implement a guessing game, I will play along if it helps you.
I don't entirely know what you mean by the enter key being taken as input. Are you typing a value into the terminal before you press enter?
String secretNum = 6;
String guess = "";
System.out.println("Guess a number between 1 and 10");
while(!guess.equals(secretNum)) {
guess = scan.next();
if(Integer.parseInt(guess)>10 || Integer.parseInt(guess)<1) {
System.out.println("Re-enter a number between one and ten");
}
}
System.out.println("You guessed it!");

y/n input validation including no input Enter key

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

I am writing a program to act like a CoinStar. Whenever I type my sentinel 'done' there is an error

`String termination;
do {
System.out.println("Begin Transaction!");
int coinNumber;
String deposit;
do{
System.out.print(">>");
coinNumber = input.nextInt();
deposit = input.nextLine();
int search = deposit.indexOf(" ", 0);
String denominations = deposit.substring(search +1);
if (coinNumber < 0){
System.out.println("Error! Please deposit positive number.");
}
else if (denominations.equalsIgnoreCase("quarter") || denominations.equalsIgnoreCase("quarters")){
Customer.insertQuarters(coinNumber);
}
else if (denominations.equalsIgnoreCase("dime") || denominations.equalsIgnoreCase("dimes")){
Customer.insertDimes(coinNumber);
}
else if (denominations.equalsIgnoreCase("nickels") || denominations.equalsIgnoreCase("nickels")){
Customer.insertNickles(coinNumber);
}
else if (denominations.equalsIgnoreCase("penny") || denominations.equalsIgnoreCase("pennies")){
Customer.insertPennies(coinNumber);
}
else if (denominations.equalsIgnoreCase("quarter") || !denominations.equalsIgnoreCase("quarters")
|| !denominations.equalsIgnoreCase("dime") || !denominations.equalsIgnoreCase("dimes")
|| !denominations.equalsIgnoreCase("nickel") || !denominations.equalsIgnoreCase("nickels")
|| !denominations.equalsIgnoreCase("penny") || !denominations.equalsIgnoreCase("pennies")
|| !deposit.equalsIgnoreCase("done")){
System.out.println("Error! Please deposit correct denominations.");
}
} while (!deposit.contains("done"));
System.out.println(Customer.getVoucher());
System.out.print("Would you like to start another transaction (y/n): ");
termination = input.nextLine();
}
while (termination.equalsIgnoreCase("y"));
System.out.println(Customer.getCollectedFees());
input.close();
}
}`
I need it to be were user inputs: (4 quarters) and as many deposits as they want. Then, types 'done' without having lines in between the deposits.
enter image description here
Thank you.
The carriage return character isn't absorbed when you make a call to nextInt(). Try placing a Scanner.nextLine() right after your initialize coinNumber:
coinNumber = input.nextInt();
input.nextLine();
deposit = input.nextLine();

while loop not working in Java

I am trying to get this to ask the question over and over again while the user inputs a 'Y'. and stop and return the Event.displayFinalResults(); when the user inputs a 'N'
i am getting a continuous loop right now. I am missing something or my layout it wrong. Any help would be great.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y')
{
do
{
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
readValidateAmountType();
readValidateAmount();
}
while(choice =='Y');
}
else
{
Event.displayFinalResults();
}
thanks again.
You program asks a Yes/No question, then if you answer Yes, it enter a loop which starts by asking the same question again, before asking for the amount value.
You might want to ask for the amount value before asking the Yes/No question again.
If user answer No, the loop will exit (after asking for one more amount value), but Event.displayFinalResults() will not be executed. Drop the else clause, so Event.displayFinalResults() whether it entered the if statement or not.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if (choice == 'Y')
{
do
{
readValidateAmountType();
readValidateAmount();
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
}
while(choice =='Y');
}
Event.displayFinalResults();
You could do this using break; as follows:
do {
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if (choice !='Y') {
break;
}
readValidateAmountType();
readValidateAmount();
} while(true);
Event.displayFinalResults();
One problem I see with this is, your while loop is inside the if statement. Once you exit the while loop, it's NOT going to run the code inside the else block because the if condition was already true.
So try removing the else block. This will make sure the Event.displayFinalResults method is called once the while loop exits.
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
Scanner keyboard = new Scanner(System.in);
char choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y')
{
do
{
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
readValidateAmountType();
readValidateAmount();
}
while(choice =='Y');
}
Event.displayFinalResults();
Clear code and compact:
Scanner keyboard = new Scanner(System.in);
char choice;
do {
System.out.println("Is there anymore amounts you want to add?(Y/N): ");
choice = keyboard.next().charAt(0);
choice = Character.toUpperCase(choice);
if(choice == 'Y') {
readValidateAmountType();
readValidateAmount();
}
} while(choice == 'Y');
Event.displayFinalResults();
Try the following out:
public void answering(char answer){
if(answer == 'Y' || answer == 'y'){
System.out.println("Answering");
} else if(answer == 'N' || answer == 'n'){
System.out.println("Not answering");
}
Instead of looping, call this method when you want to ask...

Wrong Quiz result

This is the output of the program
I was able to do till to get this result by doing this program below
import java.util.Scanner;
public class aLittleQuiz {
public static void main(String[] args) {
// declaring varibles
String quizStart;
int quizAns1, quizAns2, quizAns3;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
} else {
System.out.println("");
}
// if (quizAns == 3 && quizAns == ) {
// }
}
}
but how I can program this part?
"Overall, you got 2 out of 3 correct.
Thanks for playing!"
Declare a variable like int marks and increment it by one inside if\else block(which made for correct answer). And at the end print
System.out.println("Overall, you got" +marks+" out of 3 correct. Thanks for playing!");
Assuming your no of question is fixed( 3 )
String quizStart;
int quizAns1, quizAns2, quizAns3;
int marks=0;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
++marks;
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
++marks;
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
++marks;
} else {
System.out.println("");
}
System.out.println("Overall, you got " +marks+" out of 3 correct. Thanks for playing!");

Categories