how to break or continue a loop from user input - java

I'm trying to write a code that loops when y is entered and stops when n is entered, this is what I have so far.
Scanner input = new Scanner(System.in);
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
}while (input.hasNext());{
input.hasNext("y");
}
I have no clue how to continue.

For more readable code you can use a boolean variable and assign it to true according to your input equals to "y" condition
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean stopFlag= false;
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
String userInput =input.next();
if(!userInput.equals("y"))
stopFlag=true;
}while (!stopFlag);
}

You can do this:
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
String temp = input.next();
if(temp.equals("y")) {
// if you need to do something do it here
continue; // will go to the next iteration
} else if(temp.equals("n")) {
break; // will exit the loop
}
}

If you are persistent on using do...while then you can try:
Scanner input = new Scanner(System.in);
do{
System.out.println("She sells seashells by the seashore.");
System.out.println("Do you want to hear it again?");
}while (input.hasNext() && !input.next().equals("n"));

Related

Read in input text Yes/No Boolean from user to proceed the next step

I amm at my very beginning at java and just wanted to ask.
I want to ask the user to put Yes/No to a question and proceed to the next question. How do I do it?
import java.util.Scanner;
public class sff {
public static void main (String args[]) {
System.out.println("Hello There! We want to ask you some questions! but first: ");
System.out.print("Enter your age: ");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int age = num;
if( age == 12){
System.out.println("Hello Dan, I know you very well! ");
}
{
System.out.println("First question: ");
System.out.println("Do you exercise?(Yes/No) ");
// how do i proceed from here??
Use Scanner and get next line, then check if that line is yes or no then handle respectively.
In the example below, I used a while loop to keep asking them to input yes or no in case they enter something different like "maybe".
For example:
Scanner in = new Scanner(System.in);
// Loop until they enter either yes or no.
while(true){
String line = in.nextLine();
// Use this to check if it is yes or no
if(line.equalsIgnoreCase("yes")){
// Process yes
break;
}else if(line.equalsIgnoreCase("no")){
// Process no
break;
}else{
// Tell them to enter yes or no since they entered something else.
}
}
Are you looking for something like this?
//import to use the Scanner
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
//get the user input and store it as a String
String exerciseQuestion = in.nextLine();
//check what the user said.
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do you code when he exercises
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}
System.out.println("Ask your next question so on....");
}//main
}//class
If you want to deal with answers other than yes/no you can use this code:
import java.util.Scanner;
public class Stack_Overflow_Example {
public static void main(String[] args) {
System.out.println("First question: ");
System.out.print("Do you exercise?(Yes/No) ");
Scanner in = new Scanner(System.in);
String exerciseQuestion;
while (true){
//get the user input
exerciseQuestion = in.nextLine();
//check if user input is yes or no
if((exerciseQuestion.equalsIgnoreCase("yes")) ||
exerciseQuestion.equalsIgnoreCase("no"))
//if yes break and continue with your code
break;
else
//else loop back to get user input until answer is yes/no
System.out.println("Please answer with yes or no only");
}//while . i.e answer not yes or no
if(exerciseQuestion.equalsIgnoreCase("yes")){
System.out.println("Dan does exercise");
//do your code
}
else{
System.out.println("Dan does not exercise");
//do your not exercise code here
}//else
}//main
}//class

How do I ask the user when he/she wants to quit the program

Here's the program that I'm working on but I'm having problems with figuring out how to ask the user if they are done with it by saying a word or number.
import java.util.Scanner;
class paliindrome {
public static void main(String args[]) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
System.out.println(" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + isPalindrome.charAt(i);
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
char answer;
do {
aGame.play ();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
} while (answer == 'y' || answer == 'Y');
}
}
Put your entire application within the loop. One easy way would be to default answer to y (and you can use Character.toUpperCase(char) to eliminate the or) and something like
PalindromeChecker aGame = new PalindromeChecker();
char answer = 'y';
while (Character.toUpperCase(answer) == 'Y') {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
// ... The rest of your code ...
aGame.play();
System.out.print("\n Do you want to continue (y or n)?");
answer = keyboard.next().charAt(0);
}
There is one more way to solve your problem:
Put your entire code in a infinite while loop like this while(true), on the last line of loop just before exiting from the loop, u can ask user if he/she wants to continue. If answer is yes, then use the code System.exit(0) to exit from the program or if you want to just break from the loop use break; in the if condition.
You can use below code to ask user for quit.
boolean quit = false;
Scanner scanner = null;
try {
do {
System.out.println("Do you want to quit? (true/false)\n");
scanner = new Scanner(System.in);
String input = scanner.nextLine();
quit = Boolean.parseBoolean(input);
} while (!quit);
} finally {
scanner.close();
}
import java.util.Scanner;
public class paliindrome {
public static void main(String[] args) {
String isPalindrome, reverse = "";
Scanner in = new Scanner(System.in);
Scanner keyboard = new Scanner(System.in);
PalindromeChecker aGame = new PalindromeChecker();
for (;;) {// or while(true)
System.out.println(
" Please type a word and I'll figure out if it's a palindrome(The program is case sensitive).");
isPalindrome = in.nextLine();
int length = isPalindrome.length();
for (int i = length - 1; i >= 0; i--) {
reverse = reverse + isPalindrome.charAt(i);
}
if (isPalindrome.equals(reverse))
System.out.println("The word that you have entered is a palindrome.");
else
System.out.println("The word that you have typed isn't a palindrome.");
System.out.print("\n Do you want to continue (y or n)?");
char answer = keyboard.next().charAt(0);
if (answer != 'y' && answer != 'Y') {
break;
}else{
aGame.play ();
}
}
}
}

Scanner loop doesn't cycle when hitting enter twice

boolean loop = false;
double numberOfStudents;
System.out.print("Enter a number: ");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
while (loop) {
System.out.println("Enter a number");
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
I'm trying to get the program to say "Enter a number" until the user has entered an actual number (no white spaces or letters or signs). When the user has entered a number, it sets numberOfStudents equal to that number and breaks out of the loop.
But if you hit enter twice, it doesn't iterate. It only displays "Enter a number" once.
What is wrong with the loop logic? Why isn't it looping until valid input is taken?
For the actual answer to your question of "Why doesn't 'Enter a number' display more than once?" see Tom's comment (update: Tom's answer).
I've rewritten your loop in a way which preserves your code, but also makes it a little easier to handle format exceptions (though at the risk of silently swallowing an exception -- should be acceptable for this use case).
Can be up to you to use this design, here is an SO post on why empty catch blocks can be a bad practice.
public static void main(String args[])
{
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(loop){
System.out.print("Enter a number: ");
String input = scnr.nextLine();
try{
numberOfStudents = Double.parseDouble(input);
loop = false;
}catch(NumberFormatException e){
}
}
System.out.println("You're outside the loop!");
}
Output:
Enter a number:
Enter a number:
Enter a number:
Enter a number: 50
You're outside the loop!
First of all: Since you're reading from System.in a call to the input stream will block until the user entered a valid token.
So let's check first scan using your scnr variable:
scnr.nextLine()
nextLine() reads everything til the next line delimiter. So if you just press return, then it will successfully read it and will perform the next stuff.
The next call is:
scnr.hasNextDouble()
This call expects a "real" token and ignores white spaces, except as a delimiter between tokens. So if you just press return again it doesn't actually read that input. So it still waits for more (for the first token). That is why it stucks in your loop and you won't get another "Enter a number" output.
You can fix that by either enter a real token, like a number, or by changing the loop like trobbins said.
I hope you now understand your program flow a bit more :).
While trobbins code basically solves your problem, it's bad practice to use exceptions for flow control.
I used a small regexp to check if the value is a number. But this example is not complete, it will still crash it the user enters for example two decimal points. So you would need to create a proper number check or just use integers where the check is much easier.
Someone in the comments pointed out that people may want to enter scientific notation like 5e10, so this would also be another case to check for. If this is just some code you need as a proof of concept or something quick and dirty, you can go with the exception handling method but in production code you should avoid using exceptions this way.
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(true) {
System.out.print("Enter a number: ");
String input = scnr.nextLine().trim();
if(input.matches("^[0-9\\.]{1,}$")) {
System.out.println("Loop has stopped");
numberOfStudents = Double.parseDouble(input);
break;
}
}
System.out.println("You're outside the loop!");
The following code should help you:
double numberOfStudents = 0;
Scanner scnr = new Scanner(System.in);
boolean readValue = false; //Check if the valid input is received
boolean shouldAskForNumber = true; //Need to ask for number again? Case for Enter
do {
if (shouldAskForNumber) {
System.out.print("Enter a number:");
shouldAskForNumber = false;
}
if (scnr.hasNextDouble()) {
numberOfStudents = scnr.nextDouble();
readValue = true;
} else {
String token = scnr.next();
if (!"".equals(token.trim())) { //Check for Enter or space
shouldAskForNumber = true;
}
}
} while (!readValue);
System.out.printf("Value read is %.0f\n", numberOfStudents);
System.out.println("You're outside the loop!");
Update
Understood the following statement in question different way:
But if you hit enter twice, it doesn't loop back. It only displays
"Enter a number" once.
The code is set to print "Enter a number" only once if the user hits RETURN/ENTER or enters space character. You may remove the special check and use the code if needed.
import java.util.Scanner;
public class Testing {
public static boolean checkInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
public static void main(String[] args) {
boolean loop = false;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
String input = "";
while (!(checkInt(input))) {
System.out.println("Enter a number");
input = scnr.nextLine();
}
numberOfStudents = Integer.parseInt(input);
System.out.println("Number of students: " + numberOfStudents );
}
}
//this code is working fine, if you want you check it out.
//In your code your taking another input if the first is an int/double; if the first input is not a number then you have mentioned to take input again..
Use a debugger to see what the code is actually doing. Here's a guide on debugging in Eclipse. After you have finished debugging your code, you will probably know what the problem is.
Below code will help you
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scnr.nextLine();
while(!scnr.hasNextDouble()){
System.out.print("Enter a number: ");
try{
numberOfStudents = Double.parseDouble(input);
break;
}catch(NumberFormatException e){
}
input = scnr.nextLine();
}
System.out.println("You're outside the loop!");
The following code is working,
boolean loop = true;
double numberOfStudents;
Scanner scnr=new Scanner(System.in);
while(loop) {
System.out.println("Enter a number");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
The output is,
run:
Enter a number
hj
po
Enter a number
lhf
Enter a number
o
Enter a number
p
Enter a number
a
Enter a number
34
Loop has stopped
You're outside the loop!
You have to scan the next line if you want to get more values form the scanner again. The code should be like:
while (loop) {
System.out.println("Enter a number");
if(!(scnr.nextLine().trim().isEmpty())){
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
}

Text not printing

In school I had to make a calculator program. In the program, we ask the user if they want to add, subtract, multiply, or divide. At the end, we ask the user of they want to continue the program or no. I haven't put in the looping part yet, but my problem here is that after the "Would you like to continue" is displayed, the program just exits.
package calculator;
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
{
int o1; //first operand
int o2; //second operand
Scanner input = new Scanner (System.in);
System.out.println("Enter a choice:");
System.out.println("+ to add");
System.out.println("- to subtract");
System.out.println("* to multiply");
System.out.println("/ to divide");
System.out.println("X to exit");
String userChoice = input.nextLine();
if (userChoice.equals("X to exit")) {
System.exit(0);
}
System.out.println("Enter the first operand:");
o1 = input.nextInt();
System.out.println("Enter the second operand:");
o2 = input.nextInt();
if (userChoice.equals("+ to add")) {
System.out.println( (o1) + (o2) ); }
else if (userChoice.equals("- to subtract")) {
System.out.println( (o1) - (o2) ); }
else if (userChoice.equals("* to multiply")) {
System.out.println( (o1) * (o2) ); }
else if (userChoice.equals("/ to divide")) {
System.out.println( (o1) / (o2) ); }
System.out.println("Would you like to continue?");
System.out.println("Yes");
System.out.println("No");
String userPick = input.nextLine(); {
if (userPick.equals("Yes")) {
System.out.println("Ok."); }
else if (userPick.equals("No")) {
System.exit(0); }
}
}
}
// TODO Auto-generated method stub
}
Try this:
Scanner input = new Scanner (System.in);
while(true){
System.out.println("Enter a choice:");
System.out.println("+ to add");
......
if (userPick.equals("Yes")) {
System.out.println("Ok."); }
else if (userPick.equals("No")) {
System.exit(0); }
}
}
It will continue to loop around the logic until the terminating condition is met. You may also like to close the scanner before System.exit(); and before any termination in fact.
System.out.println("Would you like to continue?");
System.out.println("Yes");
System.out.println("No");
// add this lline, it can make a difference
input.nextLine();
String userPick = input.nextLine();
You need a while(true) {} loop at the place in the program where you want it to restart. This way, you can go back to the beginning if the user says yes, but the program will exit if the user says no.
You can add a line before your code
String userPick = input.nextLine(); which line is input.nextLine();
it can work well, which can receive enter break line.you can try.
ps:my english is bad,I am not sure I expressed clearly.

Java: Using scanner to read in boolean values failing.

import java.util.Scanner;
public class Cardhelp2{
private static String[] pairArray={"A,A","K,K","Q,Q","J,J","10,10","9,9","8,8","7,7","6,6","5,5","4,4","3,3","2,2"};
public static void generateRandom(int k){
int minimum = 0;
int maximum = 13;
for(int i = 1; i <= k; i++)
{
int randomNum = minimum + (int)(Math.random()* maximum);
System.out.print("Player " + i +" , You have been dealt a pair of: ");
System.out.println(pairArray[randomNum]);
}
} //reads array and randomizes cards
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = scan.nextInt();
generateRandom(m);
//displays the cards
___________________________________________________
System.out.println("Would you like to play?");
Scanner scanner = new Scanner(System.in);
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if(scanner.next().equalsIgnoreCase("n")||scanner.next().equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}
}
Im having trouble understanding why the end part is not working, I've been told i need to change scanner.next(); to a variable but im not sure how to do it and get the code working. Is there a simple way of reading in the users answer then displaying a response to the user?
Thanks
Your conditional expression
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes"))
calls scanner.next() twice, which means the second call will read/wait for more input. Instead you need to call it only once, store the result and use that in the comparison:
String tmp = scanner.next();
if(tmp.equalsIgnoreCase("y")||tmp.equalsIgnoreCase("yes"))
Let's assume the user inputs "yes".
At
if(scanner.next().equalsIgnoreCase("y")||scanner.next().equalsIgnoreCase("yes")) {
Scanner.next() produces "yes" in the first test. So the code is effectively
"yes".equalsIgnoreCase("y")
Which is false, so it moves to the next test:
scanner.next().equalsIgnoreCase("yes")
Here's where your issue is.
the "yes" entered has already been consumed by the first test. Now the Scanner has nothing in the buffer.
If you want to test the SAME input again, you must capture it, and use that in your tests.
So
String userReply= Scanner.next();
if(userReply.equalsIgnoreCase("y")||userReply.equalsIgnoreCase("yes")) {...
This is becauswe, with each call to scanner.next(), the Scanner returns the next value in the stream, and then MOVES PAST IT
If the user had entered "yes" and then "no", the tests would be performed like this:
if("yes".equalsIgnoreCase("y")||"no".equalsIgnoreCase("yes")) {...
You need change the way of Scanner's calls.
The user input \n and Scanner seems don't follow with the next token. Then you need read line by line.
:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many players would you like to play with? ");
int m = Integer.parseInt(sc.nextLine()); // May thrown NumberFormatException
generateRandom(m);
//displays the cards
System.out.print("Would you like to play? ");
String input = sc.nextLine();
if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
System.out.println("This will be fun");
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
System.out.println("Maybe next time");
} else {
System.out.println("Invalid character");
}
}

Categories

Resources