How to do a y/n option in a do while loop? - java

I'm wondering if anyone could steer me in the right direction, im just beginning java and i am having trouble with string validation, what i want to do here is repeat the loop for each child, repeat the loop for as many books as you want for each child and then for it to exit when there are no children left. Im struggling with the y/n option and how to make it so that only those two options are valid otherwise the user would be shown invalid option try again. Any help would be greatly appreciated!Really stumped here!
int childcounter=1;
do{
System.out.print("What is your childs first name "+childcounter+" of " +nochild+"?");
cfn=k.next();
System.out.print("What is "+cfn+"'s age?");
cage=k.nextInt();
System.out.println();
do {
System.out.print("What is the title of the book that " +cfn+ "would like?");
btitle=k.next();
System.out.print("Price of '"+btitle+"' ?");
costbook=k.nextDouble();
System.out.println();
System.out.print("Do you want to finish? y/n ");
finished=k.next();
}
while(finished.equals("N") || (finished.equals("n")));
childcounter++;
}
while (childcounter <= nochild); }

Below
System.out.print("Do you want to finish? y/n ");
String finished = k.next();
add
while (!java.util.Arrays.asList("y","n","Y","N").contains(finished)) {
System.out.println(" Invalid option. Try again.");
System.out.print("Do you want to finish? y/n ");
finished = k.next();
}

Using equalsIgnoreCase('n') would reduce the amount of code you have to type.
Use this instead.
while (finished.equalsIgnoreCase('n')
{
//method body here in the style that #halfbit suggested.
childcounter++;
}

Related

Java ArrayList loop issues

I am programming a monopoly-esque game with java on eclipse.
I am currently working on a method that allows players to loop through their own squares and choose which one to develop.
for (int loop2 = 0; loop2 < currentPlayer.getOwnedSquares().size(); loop2++) {
count++;
System.out.println("Would you like to develop this property " + count + ". "
+ currentPlayer.getOwnedSquares().get(loop2).getName() + " (y/n)");
propertyChoice = scanner.nextLine();
if (propertyChoice.equalsIgnoreCase("Y")) {
break;
}else if (propertyChoice.equalsIgnoreCase("N")) {
continue;
}
}
System.out.println("Please choose a development option");
System.out.println("1.Buy a start-up");
System.out.println("2.Buy a global corporation");
int option = scanner.nextInt();
I am unable to get the loop to present only one owned square at a time so the player can choose to select y/n for which one the want to develop. If the player was to pick "N" The loop would then present the next owned property in the array and the player would make another decision and so on..
If the player was to pick "Y" then the loop would break and move on the development options for the chosen owned square.
Any advice on how to realise this would be hugely appreciated.
You have to move the check for user input out of the loop, so the algorithm would look like this:
Print all the owned squares in a loop.
Ask user (outside the loop) which square he wants to develop. For example, a user can simply provide a positional number of a square which you can get by
currentPlayer.getOwnedSquares().get(Integer.valueOf(userInput));
Do whatever you need with selected square.
I just modified the code to test, and it works as you want. I think there is something else problematic which you haven't shared.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int count=0;
String propertyChoice;
Scanner scanner = new Scanner(System.in);
for (int loop2 = 0; loop2 < 5; loop2++) {
count++;
System.out.println("Would you like to develop this property " + count
+ " (y/n)");
propertyChoice = scanner.nextLine();
if (propertyChoice.equalsIgnoreCase("Y")) {
break;
}else if (propertyChoice.equalsIgnoreCase("N")) {
continue;
}
}
System.out.println("Please choose a development option");
System.out.println("1.Buy a start-up");
System.out.println("2.Buy a global corporation");
}
}
Output:
Would you like to develop this property 1 (y/n)
n
Would you like to develop this property 2 (y/n)
n
Would you like to develop this property 3 (y/n)
y
Please choose a development option
1.Buy a start-up
2.Buy a global corporation
Process finished with exit code 0
Try putting scanner.nextLine(); inmediately before propertyChoice = scanner.nextLine();
Edit: if this doesn't work, notice that the else has no brackets surrounding the second if block. I don't know if this will work as I do not see the classes you are refering to and cannot say there is the error. The code you've shown doesn't seem to have any other issue.

How to let the user input back to the former question

I write a code to let the user input cruise id first and then enter the ship name.
At first, I want to detect whether the user input integer type, if not, the user has to re-enter the first question again.
But in my code, it will directly print the second question instead of go back to the first question and ask again. Same, for the second question, I also want it return back and ask user to input again if the input is wrong
Please help me for that. Thanks!!
try{
System.out.println("Input Cruise ID:");
sc1 = sc.nextInt();
}catch(Exception e){
System.out.println("Please Enter integer:");
sc.nextLine();
}
System.out.println("Input ship name :");
try{
sc2 = sc.next();
}catch(Exception e){
if( sc2 != "Sydney1" || sc2 !="Melmone1"){
System.out.println("Oops!! We don't have this ship!! Please enter the ship name : Sydney1 or Melbone1");
}
}
I write a code to let the user input cruise id first and then enter the ship name. At first, I want to detect whether the user input integer type, if not, the user has to re-enter the first question again.
What you need is an input validation. try-catch block itself will not create an endless loop to reprompt the user should the input is not an integer. What you need is a while loop.
You can use a do-while loop as follows so that it runs first before performing a check:
String input = ""; //just for receiving inputs
do{
System.out.println("Input Cruise ID:");
input = sc.nextInt();
}while(!input.matches("[0-9]+")); //repeat if input does not contain only numbers
int cruiseID = Integer.parseInt(input); //actual curiseID in integer
To perform validation for your second input (i.e, your shipName, you need another while loop which encloses your prompt for input).
try-catch block are mainly used to handle exceptional cases. Try not to misuse it as a control statement for your implementations.
You can add more checks inside the while loop itself. For example, checking if the number is a negative number or zero etc. For example
while (true) {
try {
System.out.println("Input Cruise ID:");
cruiseId = sc.nextInt();
if(cruiseId <=0){
System.out.println("Please Enter integer:");
sc.nextLine();
}
break; // break when no exception happens till here.
} catch (Exception e) {
System.out.println("Please Enter integer:");
sc.nextLine();
}
}

How to ask user if he/she wants to quit the program and print out the thank you message in Java

I am taking the first Java class and working on my second project. The project is about creating an program as a network of rooms on a virtual three-dimensional work area. Each room provides a virtual environment that together can be assemble into a simulated or virtual world.
Basically, the beginning of the program, I used while loop, and at the end I want to ask user if he/she wants to quit the program, and print a thank you message. However, the while loop does not work. My program quit no matter I entered y or n. Below is my codes.
import java.util.Scanner;
public class Project
{
public static void main(String[] args)
{
Map map = new Map();
int floor = 0;
int row = 0;
int col = 0;
String input = " ";
Scanner scan = new Scanner(System.in);
// Begin user dialog. Welcome message
System.out.println("Welcome to the L.A Underground! (Verson 1.1)");
System.out.println();
String choice = "y";
while(!input.equalsIgnoreCase("quit"))
{
input = scan.nextLine().toLowerCase();
// My codes are here
if (input.equals("south")
{statement}
else
System.out.println("You can't go that way.");
else if (input.equals("quit"))
{ // See if user wants to continue
System.out.println("Do you wish to leave the Underground (Y/N)? >");
choice = scan.nextLine();
System.out.println();
}
// if user enters other words than quit
else
System.out.println("I don't recognize the word '" + input +"'");
}
System.out.println("Thank you for visiting L.A Underground.");
}
}
When I typed "quit" the console printed the message: "Do you wish to leave the Underground? (Y/N)? >". I tried Y/N (y/n) the program terminated. Any help is appreciated. Thank you.
Updated: Sorry for the confusion. What I wanted the program to run is when the user types "quit", the message will print out "Do you wish to leave the Underground (Y/N)?>?" , and if the user types "hello", the message will be "I don't understand the word 'hello'". And when the user type y, the program will quit, otherwise (type n), the program will start over again.
Ask for user input inside of your loop. If input.equalsIgnoreCase("quit"), then prompt the user an "are you sure" message. If the input.equalsIgnoreCase("y"), then break the loop, otherwise, keep going.
Scanner scan = new Scanner(System.in);
String input;
// Begin user dialog. Welcome message
System.out.println("Welcome to the L.A Underground! (Verson 1.1)");
System.out.println();
while (true) {
input = scan.nextLine();
if (input.equalsIgnoreCase("quit")) {
System.out.print("Do you wish to leave the Underground (Y/N)? >");
if (scan.nextLine().equals("y")) {
break;
}
}
// input wasn't "quit", so do other stuff here
}
System.out.println("Thank you for visiting L.A Underground.");
Your code loops until it gets "quit" ... then asks for "yes/no" ... then simply exits, regardless.
You need to change your loop, so that it includes BOTH "MY CODES HERE" AND the "quit y/n" check.
EXAMPLE:
...
boolean done = false;
while(!done) {
//MY CODES ARE HERE
if (input.equalsIgnoreCase("quit") && getYesNo ()) == 'y') {
done = true;
}
}
"getYesNo()" is a method you write. For example:
char getYesNo () {
System.out.print("Do you wish to leave the Underground (Y/N)? >");
String line = scan.nextLine();
return line.charAt(0);
}
In the code you've posted, your loop is being controlled by the condition !input.equalsIgnoreCase("quit"). That is, if input is "quit", the loop is terminated.
But the following block is executed only if input is "quit":
if (input.equals("quit"))
{
// See if user wants to continue
System.out.println("Do you wish to leave the Underground (Y/N)? >");
choice = scan.nextLine();
System.out.println();
}
So if this block is executed, !input.equalsIgnoreCase("quit") evaluates to false and the loop is terminated. And that's not what you want.
Now that you know what's wrong, fixing it is easy. Check the value of choice in the above if block: if choice is not yes, don't quit i.e. reset input to a default value.
I've pasted the working code here on pastebin.

Calling method from within itself?

ok so i have a method that displays a menu and returns the user selection.
public class Menu {
public static int menuSelect(){
Scanner input = new Scanner(System.in);
System.out.println("Hello, Please Select A Function: ");
System.out.println("1) Sort All Banks Alphabetically ");
System.out.println("2) Calculate Interest And Show Balance ");
System.out.println("3) Transfer Money ");
System.out.println("4) Calulate Sum & Average Of All Accounts: ");
System.out.println("5) Richest Account: ");
System.out.println("6) Poorest Account: ");
int select = input.nextInt();
Menu.menuSelect();
//i tried this as adding Menu.menuSelect();
//after the return threw an error.
// but surprise suprise this doesnt actually
//let the method return anythign to select
return select;
}
The idea is that i want menu to come up the user selects a function, the function happens and then the menu calls itself until told otherwise.
but im unsure how to do this.
any help would be greatly appreciated.
Calling the same method from itself is called a recursion, and it's infinite in your case. You obviously don't need it here.
You want to have something like this:
private static int getInput() {
int choice = menuSelect();
while(choice < 1 || choice > 6) {
System.out.println("Invalid choice, please re-enter")
choice = menuSelect();
}
return choice;
}
Note that it's bad to give menuSelect a public modifier, you don't want anyone outside the class to have an access to it.

Why is else statement a infinite loop?

I am fairly new to Java and I am trying to work on my data validation. The code runs fine when I use valid data, but when I put in a string instead of an integer the code just loops forever. It just loops the, "Bad input. Please enter a number." Thanks in advance!
//Get input from user
System.out.print("What is your name (Last, First)? ");
String name = scan.nextLine();
System.out.print("enter a date:");
String datein = scan.nextLine();
boolean valid = false;
while (valid != true)
{
System.out.print("Electricity used (KW):");
if (scan.hasNextDouble())
{
electricityUsed = scan.nextDouble();
valid = true;
}
else
System.out.println("Bad input. Please enter a number.");
}
because hasNextDouble always returns false.
here is the doc. You answer your own question :
but when I put in a string instead of an integer
To fix it add a scan.nextLine() to your else branch.
A simpler approach is to use the following.
System.out.print("Electricity used (KW):");
while(!scan.hasNextDouble()) {
scan.nextLine();
System.out.println("Bad input. Please enter a number.");
System.out.print("Electricity used (KW):");
}
double electricityUsed = scan.nextDouble();

Categories

Resources