How do you limit input to "yes" "no" - java

If a user answers "yes" one of the 4 quotes print, randomly generate a number between 1 out of 4 and not print it, if a user answers "no" it prints "No quotes " and if it's neither it prints "Invalid", Should i use switch? if/else?
This is Java.
public static void main(String[] args) {
Scanner keyedInput = new Scanner(System.in);
String answer;
System.out.println("Do you want to be inspired? (Enter Yes/No)");
var Gen = Math.floor(Math.random() * 4 + 1);
answer = keyedInput.nextLine();
if (answer.equals("Yes")) {
System.out.println("Quote1");
}
else if (answer.equals("Yes")) {
System.out.println("Quote2");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
else if (answer.equals("Yes")) {
System.out.println("Quote3");
}
if (answer.equals("No")) {
System.out.println("No quotes");
}
else {
System.out.println("Invalid");
}
}

This is a complex task: You want to ask the user yes/no, then if they answer neither 'yes' nor 'no', print something indicating that it's not valid and ask again.
So, make a method! And this method should loop - after all, it needs to keep doing the same thing, over and over again, until the user manages to provide a valid answer.
As a side-note, never use .nextLine(), it doesn't do what you think it does. Only use .next() if you want a string, .nextInt() if you want an int, etcetera. If you want whole lines of input (and you usually do), after making your scanner configure it to read lines at a time with scanner.useDelimiter("\\R");
public static boolean askBoolean(String prompt, Scanner scanner) {
while (true) {
System.out.print(prompt + " (yes/no): ");
String answer = scanner.next();
if (answer.equalsIgnoreCase("Yes")) return true;
if (answer.equalsIgnoreCase("No")) return false;
System.out.println("Please enter yes or no.");
}
}
Let's not use a switch, because equalsIgnoreCase sounds useful here.
and to use:
boolean wantsToBeInspired = askBoolean("Do you want to be inspired?", scanner);
if (wantsToBeInspired) {
showAQuote();
} else {
System.out.println("No quote for you");
}

I believe this is what you are trying to achieve:
int Gen = Math.floor(Math.random() * 4) + 1;
if(answer.equals("Yes")){
switch(Gen){
case 1: System.out.println("Quote 1"); break;
case 2: System.out.println("Quote 2"); break;
case 3: System.out.println("Quote 3"); break;
case 4: System.out.println("Quote 4"); break;
}
}else if(answer.equals("No")){
System.out.println("No quotes");
}else{
System.out.println("Invalid");
}

Related

.hasNextInt() in switch statement

I'm basically trying to validate so that you can only enter an Integer. This is what I have at the moment, but if I type letters it goes through the switch and just leaves the result as blank.
I want it so that if anything other than an integer is entered it will go to default in the switch.
Any help would be great. Thanks!
while(loop && kb.hasNextInt())
{
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
default :
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
If the next input is not an integer,
then .hasNextInt() will return false,
and therefore the loop will terminate early.
If you want to allow text input and respond to it,
then you need to read line by line, text instead of numbers,
and parse the line read with Integer.parseInt.
If the line cannot be parsed, you will get a NumberFormatException.
You can catch it, and handle appropriately.
while (loop && scanner.hasNextLine()) {
String line = scanner.nextLine();
try {
choice = Integer.parseInt(line);
} catch (NumberFormatException e) {
System.out.println("That is not an integer. Please try again!");
continue;
}
switch (choice) {
case 1:
language = "FRENCH";
loop = false;
break;
case 2:
language = "GERMAN";
loop = false;
break;
case 3:
language = "SPANISH";
loop = false;
break;
default:
System.out.println("That is not a correct choice. Please try again!");
break;
}
}
This is because a letter will cause your while(loop && kb.hasNextInt()) to be false. I suggest put an if statement with the hasNextInt() within the while loop.
Example (using a while loop instead of if statement to really try getting the number):
while(loop)
{
// validate int using while loop
while(!kb.hasNextInt())
{
System.out.println("you must enter a number! ");
kb.next();
}
choice = kb.nextInt();
switch(choice)
{
case 1 :
language = "FRENCH";
loop = false;
break;
case 2 :
language = "GERMAN";
loop = false;
break;
case 3 :
language = "SPANISH";
loop = false;
break;
}
}
System.out.println("Thank You " + studentID + " you have been registered for " + language);
This code will blow before it even begins if the user did not enter a number as the while required kb.hasNextInt() to be true (have a number) to even run.
What I do is that I usually put the validation around where I receive the input:
int choice;
Boolean retry = null;
while(retry == null) {
try{
String input = scanner.nextLine();
choice = Integer.parseInt(input);
retry = false;
}catch(NumberFormatException e){
System.out.println("Please enter a number from 1 to 4.");
}
}
switch(choice){
case 1:
// Do stuff
break;
case 2:
// Do stuff
break;
case 3:
// Do stuff
break;
case 4:
// Do stuff
break;
default:
System.out.println("Something went wrong!");
}

How to get two outcomes after a Do statement has been terminated?

I need two outcomes after a Do Else While statement, right now the user can input data and it will be stored in a String, if they want to add anything else they type 'y', if 'n' it will end the program and tell them what they've inputed. If they input neither of those and input 'd' for example it stops the statement running and takes me through to the Else statement
In the Else statement I want two outcomes, either "You have added the following" and "Error, you inputted something wrong"
Here is the Do Else While statement:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else {
System.out.println("You have added the following:");
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
What do I write to get two outcomes depending on what the user has done? (said 'n' or wrote something wrong).
Just add another if-else:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y"))
{
System.out.println("Enter : ");
list.add(input.next());
}
else
{
if(//valid input condition)
System.out.println("You have added the following:");
else
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
Try this:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else if (input.next().startsWith("n")) {
System.out.println("You have added the following:");
break;
} else {
System.out.println("Error, you inputted something wrong");
}
} while (true);
Introduce another condition in the else. Preferably, use else if:
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
String userInput = input.next();
if (userInput.startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} elseif (userInput.startsWith("n")) {
// user wants to stop
System.out.println("You have added the following:");
break;
} else {
System.out.println("Error, you inputted something wrong");
break;
}
} while (true);
Try to use "IF" statement inside else statement
if (input.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(input.next());
} else {
if (input.next().startsWith("n")) {
// Your code for "n"
}else{
//else here.
System.out.println("You have added the following:");
System.out.println("Error, you inputted something wrong");
break;
}
}
I think some of the logic and flow of your program is slightly off. I would change it to this.
Code:
boolean keepGoing = true; // can use a boolean to change the while loop condition to false.
while (keepGoing) {
System.out.println("Enter : ");
list.add(input.next());
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (input.next().startsWith("y")) { // 'if' to check if 'y', then execute this code.
keepGoing = true; // don't really need this, but it's here as example
} else if (input.next().startsWith("n")){ // 'else if' to check if 'n'.
System.out.println("You have added the following: " + list);
keepGoing = false; //change to false to stop the loop
} else { // and lastly a single 'else' if the input was invalid based on 2 previous conditions.
System.out.println("Error, you inputted something wrong"); // if for some reason the input isn't accepted this will show.
}
}
It follows a more logical flow and easier to understand. A simple while loop is easier for others to understand being that they can evaluate the condition before they enter the body of the loop.
You also don't need the Boolean and can simply use true in the while loop and break; in the else if portion, but as with do while loops, breaks can create confusion as far as when others need to look at your code once you start writing larger programs.

Error handling with strings java

I'm trying to add error handling to my java program if anything but the options and String/char are entered. I mainly need it for if a String is entered. I've tried to do the while(true) but I don't really understand that. I also added !(kb.hasNextInt()) to my line while (choice < 1 && choice > 4 ) but that didn't work either. So I just need help adding error handling to my program. Thanks!
here's my code
import java.util.*;
public class HeroesVersusMonsters
{
private static Hero hero;
private static Monster monster;
private static Random rand = new Random();
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
do
{
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
int choice = kb.nextInt();
kb.nextLine();
while (choice < 1 && choice > 4 )
{
System.out.println("\n" + choice + " is not an option. Please try again.");
System.out.print("Choice --> ");
choice = kb.nextInt();
kb.nextLine();
System.out.println();
}
switch (choice)
{
case 1:
hero = new Warrior();
break;
case 2:
hero = new Sorceress();
break;
case 3:
hero = new Thief();
break;
case 4:
hero = new Snake();
break;
}
switch (rand.nextInt(3))
{
case 0:
monster = new Ogre("Shrek the Ogre");
break;
case 1:
monster = new Skeleton("Bones the Skeleton");
break;
case 2:
monster = new Gremlin("Dobby the Gremlin");
break;
}
System.out.println();
System.out.println(hero.name + ", you will be fighting against " + monster.getName() + "!!!");
System.out.println();
while (hero.getHits() > 0 && monster.getHits() > 0)
{
hero.attack(monster);
monster.attack(hero);
}
System.out.print("Would you like to play again? (yes / no) ");
String play = kb.nextLine().toLowerCase();
play = play.trim();
if (play.equals("no"))
break;
else
System.out.println();
}
while (true);
}
}
Please look closly to your condition of inner while loop.
while (choice < 1 && choice > 4 )
Means loop will work until choice<1 and choice>4 remains true.
Is it exactly what you want?
I think No because what if input is 5 it is true for >4 but false for <1 what you want is you need to loop things until user enters correct input.
Am I right?
So what you need to do is just change condition like this
while(choice<1 || choice>4)
As Jared stated.
One more thing I want to suggest you don't you think you should break; external loop while user enters wrong input.(No problem)
You can do one this also.
ArrayList<Integer> ar=new ArrayList<Integer>(4);
ar.add(1);
ar.add(2);
ar.add(3);
ar.add(4);
while(true)
{
if(ar.contains(choice))
{
//Go On
}
else
{
//Print old stuff
}
}
Here is what your main method should look like:
public static void main(String ...args){
final Scanner scanner = new Scanner(System.in);
while(true){
final Hero hero = promptHero(scanner);
final Monster monster = getRandomMonster();
fight(hero, monster);
if(!playAgain(scanner))
break;
}
}
Now write the static methods promptHero, getRandomMonster, fight, and playAgain (which should return true if you want to play again).
Here is what your promptHero method should look like (to properly handle bad input):
private static Hero promptHero(final Scanner scanner){
while(true){
System.out.println("---------------------------------------");
System.out.println("\tChoose your type of hero");
System.out.println("---------------------------------------");
System.out.println("\t1. Warrior");
System.out.println("\t2. Sorceress");
System.out.println("\t3. Thief");
System.out.println("\t4. Snake");
System.out.println();
System.out.print("Choice --> ");
try{
final int choice = scanner.nextInt();
if(choice < 1 || choice > 4)
System.out.println("\n" + choice +
" is not an option. Please try again.");
else
return getHero(choice); //return the hero
} catch(InputMismatchException ime){
final String line = scanner.nextLine();// need to advance token
System.out.println("\n" + line +
" is not an option. Please try again.");
}
}
}
private static Hero getHero(final int choice){
switch (choice){
case 1:
return new Warrior();
case 2:
return new Sorceress();
case 3:
return new Thief();
case 4:
return new Snake();
}
return null;
}
You should check out the Java regex:
if(choice.toString().matches("[0-9]+"))
{
//continue
}
else
{
//error message
}

Syntax error on token "else", delete this [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I keep on getting this error and I tried mixing it around. But then when I choose the option, it does the option, but then said "you did not enter 1, 2 or 3".
This is the the full code. How to fix it?
The error is at
} else {
System.out.println("You did not enter 1, 2 or 3");
} else {
System.out.println("The Pin You Entered Was Wrong");
}
This is an incorrect syntax:
}else{
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
Just do it this way:
else {
System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}
The problem is in the code you provided on your paste bin.
You use two else statements, so Java complains as it doesn't know which to go to after the initial if statement.
You need to enter in another conditional statement using else if, then else. For example:
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
etc
}else if (nothing entered) {
System.out.println("You did not enter 1, 2 or 3");
}else{
System.out.println("The Pin You Entered Was Wrong");
}
You also have another major problem with your code. You declare the variable option and set it in an if statement, so it only has scope within that if statement. You then come out of the if statement and declare a brand new option variable before the code I provided above. This will not function, as the option integer has no value.
Instead, you need to declare your initial option int outside of your if statement, like so:
int number;
int password = 7123;
int amount = 4000;
int option;
if (number == password) {
etc...
option = userInput.nextInt();
}
Furthermore, you come out of the if statement checking the entered number against the stored password to take input on withdrawing cash etc. This is no good. It means that after the if statement checking number against password is finished, it will automatically proceed to the next block of code.
As the scanner object hasn't been created, the first three if statements will come back false and your else statement will be printed (regardless of whether the input password was correct).
Therefore, I would advise you to put that check in a separare else statement and use a while loop to confirm a correct selection ahs been entered. For example:
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
int option;
number = userInput.nextInt();
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
while (option != 1 || option != 2 || option != 3) {
System.out.println("You didn't enter a valid number. Try again");
option = userInput.nextInt();
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
else if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
else if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}
}
else
System.out.println("The Pin You Entered Was Wrong");
}
your second else statement does not close no if statement.
Also, the option variable is not in the right scope:
try this
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome To Harry's Bank");
//Pin System
System.out.println("Please Enter Your Bank Pin.");
Scanner userInput = new Scanner (System.in);
int number;
int password = 7123;
int amount = 4000;
number = userInput.nextInt();
int option;
if (number == password) {
System.out.println("Pin Accepted");
System.out.println("You Have Now Entered Harry's Bank!");
System.out.println("Press The Number Of The Option You Would Like.");
System.out.println("1.Withdraw Money.");
System.out.println("2.Put In Money");
System.out.println("3.Exit Bank");
Scanner Options = new Scanner (System.in);
option = userInput.nextInt();
}else{
System.out.println("The Pin You Entered Was Wrong");
}
if (option == 1){
Option_1 Optionone = new Option_1();
Optionone.Withdraw();
}
if (option == 2){
Option_2 Optiontwo = new Option_2();
Optiontwo.Deposit();
}
if (option == 3){
Option_3 Optionthree = new Option_3();
Optionthree.Exit();
}else{
System.out.println("You did not enter 1, 2 or 3");
}
}
}
The problem is that you the 'else' statement twice in your if-else construct.
You have:
if { }
else { }
else { }
But you probably want:
if { }
else if { }
else { }
You cannot have TWO else in a if-else case.
Your nested If statement is not proper. Use it as below
if (number == password) {
.....
.....
if (option == 1) {
}
else if (option == 2) {
}
else if (option == 3) {
} else {
System.out.println("You did not enter 1, 2 or 3");
}
} else {
System.out.println("The Pin You Entered Was Wrong");
}
You can't have two else blocks added to an if
} else {
System.out.println("You did not enter 1, 2 or 3");
} else {
System.out.println("The Pin You Entered Was Wrong");
}
Either drop one or club the two println()s into one else block
} else {
System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}
Take a look at how to use the if-then and if-then-else statements.
Alternatively, I suggest you to make use of the Switch statements for better clarity of code.
switch (option) {
case 1: Option_1 OptionOne = new Option_1();
OptionOne.Withdraw();
break;
case 2: Option_2 OptionTwo = new Option_2();
OptionTwo.Withdraw();
break;
case 3: Option_3 OptionThree = new Option_3();
OptionThree.Withdraw();
break;
default: System.out.println("You did not enter 1, 2 or 3");
System.out.println("The Pin You Entered Was Wrong");
}

Java exception handling Do loop not working?

Here is the code:
package classes;
import java.util.*;
public class Introduction {
Scanner Input = new Scanner(System.in);
int classChoose;
boolean repeat = false;
public void Introduction() {
System.out.println("\t===THE QUEST FOR PERSEPOLIS===\tv 1.0\n");
System.out.println("Please choose a class: ");
System.out.print("(1)Elite Knight\t");
System.out.print("(2)Dawnguard\n");
System.out.print("(3)Archer\t\t\t");
System.out.print("(4)Barbarian\n");
System.out.print("(5)Mage\t\t\t");
System.out.print("(6)Swordsman\n");
System.out.println("(7)Crossbowman\t");
do {
try {
repeat = false;
classChoose = Input.nextInt();
while(classChoose < 1 || classChoose > 7) {
repeat = false;
System.out.println("Error. Enter a number between 1 and 7(inclusive).");
classChoose = Input.nextInt();
}
}
catch(InputMismatchException e) {
repeat = true;
System.err.println("Caught: "+e);
Input.nextLine();
}
}while(repeat = true);
switch(classChoose) {
case 1: chooseKnight();
break;
case 2: chooseGuard();
break;
case 3: chooseArcher();
break;
case 4: chooseBarbarian();
break;
case 5: chooseMage();
break;
case 6: chooseSwordsman();
break;
case 7: chooseCrossbowman();
break;
}
}
public static void chooseKnight() {
System.out.println("You have chosen the Elite Knight. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseGuard() {
System.out.println("You have chosen the Dawnguard. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseArcher() {
System.out.println("You have chosen the Archer. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseBarbarian() {
System.out.println("You have chosen the Barbarian. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseMage() {
System.out.println("You have chosen the Mage. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseSwordsman() {
System.out.println("You have chosen the Swordsman. You will be briefed and then you shall be set "
+"on your quest!");
}
static void chooseCrossbowman() {
System.out.println("You have chosen the Crossbowman. You will be briefed and then you shall be set "
+"on your quest!");
}
}
Everytime I run it, the program prompts me to choose my class. After I enter my choice, the program does not go on to the switch statement below the do loop. Can someone help me fix this?
-Calvin
This is an assignment:
while(repeat = true); // Note single '=', not '=='
and the result of which will always be true, from section 15.26 Assignment Operators of the Java Language Specification:
At run time, the result of the assignment expression is the value of the variable
after the assignment has occurred.
Change to:
while(repeat);
while(repeat = true);
should be: -
while(repeat == true); // Or better: - while(repeat);
And in your catch, change Input.nextLine() to Input.next() : -
catch(InputMismatchException e) {
repeat = true;
System.err.println("Caught: "+e);
Input.nextLine(); // Change to Input.next()
}
And your instance variable should begin with a lowercase alphabet or an underscore.. So change Input to input.

Categories

Resources