i had this problem where while looping, the output shows the loop but the invalid is also there. how do i separate the loop and the if...else statements?
below is the program code.
Scanner scan = new Scanner(System.in);
String option = new String("Y");
while (option.equalsIgnoreCase("Y")) {
System.out.println("Good Morning!!");
System.out.print("Do you want to continue [Y/N]: ");
option = scan.nextLine();
if (option.equalsIgnoreCase("N")) {
break;
} else {
System.out.println("invalid");
}
}
this is the output of the loop. the invalid is only supposed to show up when i put in a different letter other than y or n
Do you want to continue [Y/N]: y
invalid
Good Morning!!
Do you want to continue [Y/N]: y
invalid
Good Morning!!
and it was supposed to show like this
Good Morning!!
Do you want to continue [Y/N]: y
Good Morning!!
Do you want to continue [Y/N]: y
Good Morning!!
Do you want to continue [Y/N]: n
You're just cheking if it's a "N" but not a "Y" so it'll will show invalid for Y. You just have to add another else if and the last else with the invalid.
Scanner scan = new Scanner(System.in);
String option = new String("Y");
while (option.equalsIgnoreCase("Y")) {
System.out.println("Good Morning!!");
System.out.print("Do you want to continue [Y/N]: ");
option = scan.nextLine();
if (option.equalsIgnoreCase("N")) {
break;
}else if(option.equalsIgnoreCase("Y")){
continue;
}else {
System.out.println("invalid");
}
}
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Good Morning!!");
System.out.print("Do you want to continue [Y/N]: ");
String option = scan.nextLine().toUpperCase();
if ("N".equals(option))
break;
if ("Y".equals(option))
continue;
System.out.println("invalid");
}
You could also implement else if to check for acceptable character and remove the redundant check from the condition in while:
while (true) {
System.out.println("Good Morning!!");
System.out.print("Do you want to continue [Y/N]: ");
String option = scan.nextLine();
if (option.equalsIgnoreCase("N")) {
break;
} else if (!option.equalsIgnoreCase("Y")) {
System.out.println("invalid");
}
}
Related
So I have a while-loop where you have 3 options to choose from and you choose them by inserting a number on standard input using a scanner, my code is like this:
int option;
String request;
Scanner input2 = new Scanner(System.in);
System.out.println("Choose an option:\n" + "1-Get camera information\n" + "2-Submit Data\n"
+ "3-Exit");
while(true){
try {
option = input2.nextInt();
if (option == 1) {
System.out.println("Camera name:");
request = input2.nextLine();
while (request.length() < 3 || request.length() > 15) {
System.out.println("Name has to be between 3 and 15 characters, insert a new one:");
request = input2.nextLine();
}
CamInfoRequest info_request = CamInfoRequest.newBuilder().setName(request).build();
if (stub.camInfo(info_request).getReturn() != 0) {
System.out.println("Camera does not exist");
} else {
System.out.println(stub.camInfo(info_request).getLatitude() + " " + stub.camInfo(info_request).getLongitude());
}
} else if (option == 2) {
System.out.println("submit");
} else if(option ==3){
break;
} else{
System.out.println("Invalid option.");
}
}catch(InputMismatchException e){
System.out.println("Invalid input");
}
}
So the way this is the code enters in an infinite loop when it catches the exception where it keeps printing "Invalid input", I tried using input2.next() at the catch but then he waits for another input I don't want, I can't use input2.close() either. What can I do?
I can't use input2.close() either.
You should never close the Scanner instance for System.in as it also closes the System.in.
I tried using input2.next() at the catch but then he waits for another
input I don't want
Use Scanner::nextLine instead of Scanner::next, Scanner::nextInt etc. Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn why.
Also, try to use do...while wherever you need to ask the user to enter the data again in case of an invalid entry.
Given below is a sample code incorporating these points:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int option;
boolean valid;
Scanner input2 = new Scanner(System.in);
do {
valid = true;
System.out.println("Choose an option:\n" + "1-Get camera information\n" + "2-Submit Data\n" + "3-Exit");
try {
option = Integer.parseInt(input2.nextLine());
if (option < 1 || option > 3) {
throw new IllegalArgumentException();
}
// ...Place here the rest of code (which is based on the value of option)
} catch (IllegalArgumentException e) {
System.out.println("This is an invalid entry. Please try again.");
valid = false;
}
} while (!valid);
}
}
A sample run:
Choose an option:
1-Get camera information
2-Submit Data
3-Exit
abc
This is an invalid entry. Please try again.
Choose an option:
1-Get camera information
2-Submit Data
3-Exit
6
This is an invalid entry. Please try again.
Choose an option:
1-Get camera information
2-Submit Data
3-Exit
2
Feel free to comment in case of any further doubt/issue.
Just Put the Scanner statement inside your try block
while (true) {
try {
Scanner input2 = new Scanner(System.in);
option = input2.nextInt();
if (option == 1) {
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...
I'm currently creating my first game which is executed in a console.
I've been asked to validate an input which can be done with a simple code. The goal is to input, and then validate if that number is an integer, and is on a range of 1-4. If possible, the problem should be solved with basic algorithm.
The problem is that it won't give me the result I wanted. It works when I enter a string, but it loops on every number I put including the number in the range. Does anyone know why?
public class Menu {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
if (!scanner.hasNextInt()) {
inputValidate = false;
System.out.println("Not a number. Please input number 1-4.");
scanner.nextLine();
} else if (input <= max && !(input < min)) // if input <= 4 and input is not less than 1
{
input = scanner.nextInt();
inputValidate = true;
} else {
inputValidate = false;
System.out.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
switch (input) {
case 1:
break;
case 2:
System.out.println("Good work!");
break;
case 3:
break;
case 4:
break;
}
}
}
}
Because you instantiate input to be 0, but never give the user an opportunity to change this, the conditions for the first two conditionals are always false (nothing is read from the Scanner and 0 is not between min and max). Therefore, the program falls through to the else every time. Just add a statement before the do-while that will obtain a value for input from the user.
input = scanner.nextInt();
// your do-while loop
(You'll also probably have to adjust the code slightly to get the type of interaction you're looking for. Hint - you're reading two values from the user.)
As Clint said the problem was in your input. Here's a demo how you can fix this,
try (Scanner scanner = new Scanner(System.in)) {
int input = 0;
int min = 1;
int max = 4;
boolean inputValidate = false;
System.out.println("Main Menu");
System.out.println("=========");
System.out.println("1. Play Game");
System.out.println("2. About");
System.out.println("3. View Saved Games");
System.out.println("4. Exit");
System.out.println("");
do {
System.out.print(">> ");
try {
input = scanner.nextInt();
if (input >= min && input <= max) {
inputValidate = true;
} else {
System.out
.println("Not in range. Please input number 1-4.");
scanner.nextLine();
}
} catch (InputMismatchException exception) {
System.out
.println("Not a number. Please input number 1-4.");
scanner.nextLine();
}
} while (!(inputValidate));
I am trying to create a program that will check the password of the user. I want the program to end once the user gets it correct but if not I want it to ask only 4 times.
Problem: even if you do get the password correctly the program keeps on asking guess the password. And if you get it wrong it will ask incorrectly. How can I fix this?
import java.util.Scanner;
public class HowToAdd {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
int trys = 0;
String password=null;
do{
System.out.println("Guess the password");
password = input.next();
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
}else{
System.out.println("Try again");
input.next();
trys++;
}
}while(trys<2);
System.out.println("Try again later!");
input.close();
}
}
You just need to add a break:
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}
Not only did I add a break to fix the problem of not leaving the loop when correct password is entered but I added a couple of other things to help you out see below:
public static void main (String [] args){
Scanner input = new Scanner (System.in);
int trys = 0;
String password=null;
System.out.println("Guess the password:");
while(trys<2)
{
password = input.next();
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}else{
trys++;
if(trys != 2)
{
System.out.println("Try again:");
}
}
}
if(trys == 2)
{
System.out.println("Try again later!");
}
input.close();
}
Try this it will break out of the loop if it is correct using the break; statement. Also it will only display guess a password the first try then try again after that. Also it won't say try again later if they guessed right because it checks if they guessed wrong twice.
You can fix it with a break keyword, like so :
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}
The break is explained here :
Branching Statements
What you need to implement can be done without using break statements.
Try to look at the flow of my codes.
Scanner scn = new Scanner(System.in);
int tries=0;
String pw = "";
System.out.println("Guess the password");
pw = scn.nextLine();
while(!pw.equalsIgnoreCase("Password") && tries < 3){
tries++;
System.out.println("Try again");
pw = scn.nextLine();
}
if(tries >= 3)
System.out.println("Try again later!");
else
System.out.println("Great job!");
TEST RUN 1:
Guess the password
1st try
Try again
2nd try
Try again
3rd try
Try again
last try
Try again later!
TEST RUN 2:
Guess the password
password
Great job!
Here is another variant of code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int trys = 0;
String password = null;
// create variable for a number of tries
int numberOfCheks = 4;
do {
System.out.println("Guess the password");
password = input.nextLine();
if (password.equalsIgnoreCase("Password")) {
System.out.println("Great job");
break;
} else if (++trys == numberOfCheks) {
//Break if you've used all your tries
System.out.println("Try again later!");
break;
} else {
System.out.println("Try again");
// input.next(); - Useless. You don't handle it. Removed
}
//There is already tries number check. So 'true' can be used as the condition.
} while (true);
input.close();
}
This code checks if the users input it is valid. if it is not a number it will continue to loop untill it receives a number. after that it will check if that number is in bounds or lesser than than the bound. it will continue looping until it receives an inbound number. but my problem here is that when I print choice it only shows the previous number after the last number that was inserted. why is it like that?
public void askForDifficulty(){
System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: ");
int choice = 0;
boolean notValid = true;
boolean notInbound = true;
do{
while(!input.hasNextInt()){
System.out.println("Numbers Only!");
System.out.print("Try again: ");
input.nextLine();
}
notValid = false;
choice = input.nextInt();
}while(notValid);
do{
while(input.nextInt() > diff.length){
System.out.println("Out of bounds");
input.nextLine();
}
choice = input.nextInt();
notInbound = false;
}while(notInbound);
System.out.println(choice);
}
This is because input.nextInt() inside the while condition consumes the integer, so the one after it reads the following one. EDIT You also need to combine the two loops, like this:
int choice = 0;
for (;;) {
while(!input.hasNextInt()) {
System.out.println("Numbers Only!");
System.out.print("Try again: ");
input.nextLine();
}
choice = input.nextInt();
if (choice <= diff.length) break;
System.out.println("Out of bounds");
}
System.out.println(choice);