How to keep the program running if the user entered Y? - java

Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
{
System.out.println("What is the answer to the following problem?");
Generator randomNum = new Generator();
int first = randomNum.num1();
int second = randomNum.num2();
int result = first + second;
System.out.println(first + " + " + second + " =");
int total = Keyboard.nextInt();
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
}
}
}
}
I'm trying to keep the program to continue but if the user enters y and closes if he enters n.
I know that I should use a while loop but don't know where should I start the loop.

You can use a loop for example :
Scanner scan = new Scanner(System.in);
String condition;
do {
//...Your code
condition = scan.nextLine();
} while (condition.equalsIgnoreCase("Y"));

That is a good attempt. Just add a simple while loop and facilitate user input after you ask if they want to continue or not:
import java.util.*;
class Main
{
public static void main(String [] args)
{
//The boolean variable will store if program needs to continue.
boolean cont = true;
Scanner Keyboard = new Scanner(System.in);
// The while loop will keep the program running unless the boolean
// variable is changed to false.
while (cont) {
//Code
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
}
}
}
}
You may also read up on other kinds to loop and try implementing this code in other ways: Control Flow Statements.

Related

Repeat a loop already satisfied in java

I'm looking to repeat a "game" if it is already satisfied in my case where user has to guess the random number. I can't understand where to to get back to the main game unless i have to create another "do - while" loop inside it and retype the game again in the section where it says: System.out.println("you have tried: " + count + " times. Would you like to play again? y/n"). Is there a way to just bring back to the actual guess loop rather than create another one?
Hopefully makes sense.
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
int guess;
int count;
count = 0;
int num;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
**System.out.println("you have tried: " + count + " times. Would you like to play again? y/n");**
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
}
The simplest solution would be to move the entire "guess loop" into a separate method. Then in the case when you want it to repeat, just call the method recursively.
If you want to reuse code you can make functions (or methods here, because we are inside a class). They can be used to encapsulate code and call it from anywhere to use it.
You can define a methods like that:
public static void methodName() {
// code go here
}
Then, you can call it from anywhere like that :
pass.methodName(); // It will execute the code inside methodName()
In reality, this is a lot more complex than that, you can give methods values and return others, change the scope of it to make it internal only or reachable by other classes. But I presume that you are a beginner so I keep it simple. I strongly recommend you to make a quick research about Object Oriented Programmation!
For your code, you can put the game's while loop in a method and call it at the beginning and each time the player wants to restart the game. Good luck with your game!
I manage to do this way. It seems working but one thing is letting me down at the very last when I key in "n" or other key than "y". Exception in thread "main" java.util.InputMismatchException. Is there a more softer way to finish it?
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class pass {
public static void randomnum(){
Scanner scanner = new Scanner(System.in);
int guess;
int count;
count = 0;
int num;
do {
num = ThreadLocalRandom.current().nextInt(1,10);
guess = scanner.nextInt();
count++;
if (guess == num) {
System.out.println(" Well done!");
System.out.println("you have tried: " + count + " times.");
String answer;
do{
System.out.println("Do you want to play again? y/n");
answer = scanner.next();
if (answer.equals("y")) {
System.out.println("let's play again");
randomnum();
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
}
else {
System.out.println("you are logout!");
break;
}
}while (answer.equals("Y"));
randomnum();
}
else if (guess < num) {
System.out.println("your number is smaller than the number given");
}
else {
System.out.println("your guess is too high");
}
} while (guess != num);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pass = "password123";
String input;
do {
System.out.print("Enter your password: ");
input = scanner.next();
} while (!input.equals(pass));
System.out.println("Correct! Now play the guess game! Guess a number between 1 - 10.");
randomnum();
}
}

Recursively getting string user input with Scanner class in java

So, I want to receive input from the user, check if they used alphabetical values and then check if it is too long. If too long, I want to start again from the top (checking if alphabetical) by calling the method I am in. However, when I start over and I type, say "Danny", this will show:
Output: "Thank you, got Danny"
Output: (length of previous, too long input) + "is too many characters, try to keep it under 30."
So somehow, it keeps the original input (that was alphabetical, but above 30) saved and it doesn't alter it when it starts over. Anyone know what I should do instead?
public static String inputPattern() {
Scanner scanner = new Scanner(System.in);
String player;
int strLength;
System.out.println("Please enter your name:");
while (!scanner.hasNext("[A-Za-z]+")) { //Checks if alphabetical value
System.out.println("Please stick to the alphabet!");
scanner.next();
}
player = scanner.next();
player += scanner.nextLine();
System.out.println("Thank you! Got " + player);
strLength = player.length(); // Saves the length of user-inputted name
while (strLength > 30) { // Checks if not too long
System.out.println(strLength + " is too many characters, please try to keep it under 30");
inputPattern(); // Starts over again if too long
}
return player;
}
I have taken your method and modified it a bit.
It is non recursive solution.
Also in your code scanner resource was not closed at the end.
Iterative Solution
import java.util.Scanner;
public class SO66064473 {
public static void main(String[] args) {
inputPatternIterative();
}
public static String inputPatternIterative() {
Scanner scanner = new Scanner(System.in);
String player = "";
int strLength = Integer.MAX_VALUE;
while (strLength > 30) { // Checks if not too long
System.out.println("Please enter your name:");
while (!scanner.hasNext("[A-Za-z]+")) { //Checks if alphabetical value
System.out.println("Please stick to the alphabet!");
scanner.next();
}
player = scanner.next();
player += scanner.nextLine();
System.out.println("Thank you! Got " + player);
strLength = player.length(); // Saves the length of user-inputted name
if (strLength > 30)
System.out.println(strLength + " is too many characters, please try to keep it under 30");
}
scanner.close(); // Closing scanner resource after use.
return player;
}
}
Output :
Please enter your name:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Thank you! Got aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
70 is too many characters, please try to keep it under 30
Please enter your name:
aaaaaaaaaaaaaaaaaaaa12
Please stick to the alphabet!
coifvoifoivmrfvoirvoirovroijfoirjfoijroifjrwofjorwfouwrfoijwrofjworjfoiwrjf
Thank you! Got coifvoifoivmrfvoirvoirovroijfoirjfoijroifjrwofjorwfouwrfoijwrofjworjfoiwrjf
75 is too many characters, please try to keep it under 30
Please enter your name:
Danny
Thank you! Got Danny
EDIT : with the suggestion made by #Dev-vruper here is updated easy recursive code
Recursive Solution
import java.util.Scanner;
public class SO66064473 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
inputPatternRecursive(sc);
sc.close();
}
public static String inputPatternRecursive(Scanner sc) {
System.out.println("Please enter your name:");
String player = sc.nextLine();
if (!player.matches("[A-Za-z]+")) {
System.out.println("Please stick to the alphabet!");
inputPatternRecursive(sc);
} else {
System.out.println("Thank you! Got " + player);
if (player.length() > 30) {
System.out.println(player.length() + " is too many characters, please try to keep it under 30");
inputPatternRecursive(sc);
}
}
return player;
}
}
This should solve your problem in a pretty easy way:
public static String inputPattern(){
Scanner scanner = new Scanner(System.in);
String player = "";
int strLength;
boolean bShowedInstruction = true;
System.out.println("Please enter your name:");
while (true) {
if (!bShowedInstruction)
System.out.println("Please enter your name:");
bShowedInstruction = false;
player = scanner.next();
if (!player.matches("[A-Za-z]+")) {
System.out.println("Please stick to the alphabet!");
}
else if (player.length() > 30) {
System.out.println(player.length() + " is too many characters, please try to keep it under 30!");
}
else
break;
}
System.out.println("Thank you! Got " + player);
return player;
}
There's no need for a recursion. A simple while(true) loop does the trick.
It's a pretty clean solution keeping unnecessary scan-methods out of the game.

How to repeat a question to a user until while loop condition is false?

I'm bulding a console application where I am trying to force a user to enter an int as a possible answer to a question otherwise the same question is repeated to the user.Thus, the user cannot move on without entering the proper data type.
below is my sample code.
Scanner scanner = new Scanner(System.in);
int userInput = 0;
do {
AskQuestion();
if(scanner.hasNextInt()) {
userInput = scanner.nextInt();
}
}
while(!scanner.hasNextInt()) ;
While I know this can be done in C#, I'm not exactly sure how to do it in java without getting stuck in an infinite loop. How do I get my code to do what I want to do? Please help!
You can use something like this. It'a a pretty simple flag combined with the use of the Scanner class.
boolean flag = false;
int val = 0;
while(!flag){
System.out.println("Something");
if(sc.hasNext()){
if(sc.hasNextInt()){
val = sc.nextInt();
flag = true;
}
else{
sc.next();
}
}
}
Try this:
Scanner scanner = new Scanner(System.in);
int userInput;
while(true) {
AskQuestion();
if (scanner.hasNextInt()) {
userInput = scanner.nextInt();
break;
}
scanner.next(); // consume non-int token
}
Another alternative which utilizes the Scanner#nextLine() method along with the String#matches() method and a small Regular Expression (RegEx) to ensure that the supplied string does indeed contain all numerical digits:
Scanner scanner = new Scanner(System.in);
String userInput = "";
int desiredINT = 0; // Default value.
while (desiredINT == 0) {
AskQuestion();
userInput = scanner.nextLine();
if (userInput.matches("\\d+")) {
desiredINT = Integer.parseInt(userInput);
if (desiredINT < 1 || desiredINT > 120) {
System.out.println("Invalid Input! The age supplied is not "
+ "likely! Enter a valid Age!");
desiredINT = 0;
}
}
else {
System.out.println("Invalid Input! You must supply an Integer "
+ "value! Try Again...");
}
}
System.out.println("Your age is: --> " + desiredINT);
And the AskQuestion() method:
private void AskQuestion() {
System.out.println("How old are you?");
}
This is nice and short one
Scanner scanner = new Scanner(System.in);
do askQuestion();
while(!scanner.nextLine().trim().matches("[\\d]+"));
Tell me if you like it
Note it just tell you if number was an int , and keeps repeating if not, but doesn't give you that int back , tell me if you need that, i shall find a way
My solution might be a bit bloated, but I hope it's nice and clear what's going on. Please do let me know how it can be simplified!
import java.util.Scanner; // Import the Scanner class
class Main {public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
String unit;
// unit selector
while (true) {
System.out.println("Did you measure ion feet or meters? Type 'meters' or 'feet': ");
String isUnit = myObj.nextLine();
if (isUnit.equals("feet") || (isUnit.equals("meters"))) {
unit = isUnit;
break;
} else {
System.out.println("Please enter either 'meters' or 'feet'.");
}
}
System.out.println("Use selected " + unit);
}

How to end a while loop [duplicate]

This question already has answers here:
Cant figure out how to exit the loop of my program
(3 answers)
Closed 6 years ago.
My program for class asks to run the program as long as the user doesn't enter the input of -99. When I run the program and enter a usable number that isn't -99, the console will run a continuous looping answer until I have to press end.
How can I change the program so for each input there will be one answer and the program restarts until user inputs -99?
import java.util.Scanner; //import scanner
import java.io.*; //import library
public class is_odd_or_even_number {//begin class
public static void main(String []args) {//begin main
Scanner input = new Scanner(System.in);
//use try/catch method to test for invalid input
try{
//promt user to input a value
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
//PART I NEED HELP WITH **************
while (number != -99){
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else
System.out.println("Your number is Odd!");
}
}
//open catch method and print invalid
catch(Exception notNumber) {
System.out.println("Input not a number, try again.");
}
}
//begin testing for odd or even in new method
public static boolean isEven(int num){
return(num & 1) == 0;
}
}
Here, you don't let the user entry other thing that the first input before the loop.
The retrieval of the input from the user :
int number = input.nextInt();
should be in the loop.
Try that :
int number = 0;
//PART I NEED HELP WITH **************
while (number != -99){
number = input.nextInt();
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else
System.out.println("Your number is Odd!");
}
}
You can do like this way ;)
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
//PART I NEED HELP WITH **************
while (number != -99){
System.out.print("Not good, please enter a new one : ");
number = input.nextInt();
}
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else {
System.out.println("Your number is Odd!");
}
So it will ask until you're not writing -99 as you said, but if you're asking for "a positive int" normally nobofy would write -99 :p
End a while loop
You can use a boolean value shouldContinue to control whether the programs should continue to the next input.
if (number != -99) {
shouldContinue = true;
} else {
shouldContinue = false;
}
This can be simplified as follow:
shouldContinue = number != -99 ? true : false;
// or even shorter
shouldContinue = number != -99;
Read the value correctly
But you need to ensure that you input number is reset at each loop execution so that you can read the next number:
while (shouldContinue) {
...
number = input.nextInt();
}
Other enhancements
Do not import unused packages or classes
Use camel case for Java class name
Use comment style /** ... */ for Javadoc
Always try to avoid infinite loop, e.g. use an integer count tries and count down at each loop.
Here's the final answer look like:
import java.util.Scanner;
public class IsOddOrEvenNumber {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
boolean shouldContinue = true;
int tries = 0;
while (shouldContinue && tries < 10) {
try {
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
if (isEven(number)) {
System.out.println("Your number is Even!");
} else {
System.out.println("Your number is Odd!");
}
shouldContinue = number != -99 ? true : false;
} catch (Exception notNumber) {
System.out.println("Input not a number, try again.");
}
tries--;
}
System.out.println("Game over.");
}
/**
* Begin testing for odd or even in new method
*/
public static boolean isEven(int num){
return (num & 1) == 0;
}
}
Here you are the main method which will be running as long as user is not entering -99;
You should include all your code in the while loop (even try/catch).
public static void main(String []args) {//begin main
Scanner input = new Scanner(System.in);
int number = 0;
//Keep application running as long as the input is not -99
while (number != -99){
//use try/catch method to test for invalid input
try{
//promt user to input a value
System.out.print("Enter a positive integer value: ");
number = input.nextInt();
//Start of if statement to test which to print and call of isEven method
//if the entered number is -99, the following code will skipped.
if(number == -99) continue;
if (isEven(number))
System.out.println("Your number is Even!");
else
System.out.println("Your number is Odd!");
}
//open catch method and print invalid
catch(Exception notNumber) {
System.out.println("Input not a number, try again.");
}
}
}
You could accept this answer, in case it is what you are looking for :)

Why is my try and catch stuck in a loop?

I want the user to enter integers into an array. I have this loop I wrote which has a try and catch in it, in case a user inserts a non integer. There's a boolean variable which keeps the loop going if is true. This way the user will be prompted and prompted again.
Except, when I run it, it gets stuck in a loop where it repeats "Please enter # " and "An Integer is required" without letting the user input a new number. I reset that number if an exception is caught. I don't understand.
import java.util.*;
public class herp
{
//The main accesses the methods and uses them.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array"+" and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize+1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length)
{
// Not into will turn true and keep the loop going if the user puts in a
// non integer. But why is it not asking the user to put it a new checkint?
while(notint)
{
try
{
notint = false;
System.out.println("Please enter #"+ prompt);
checkint = scan.nextInt();
}
catch(Exception ex)
{
System.out.println("An integer is required." +
"\n Input an integer please");
notint = true;
checkint = 1;
//See, here it returns true and checkint is reset.
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
}
}
Once the scanner has thrown an InputMismatchException it cannot continue to be used. If your input is not reliable, instead of using scanner.nextInt() use scanner.next() to obtain a String then convert the string to an int.
Replace:
checkint = scan.nextInt();
With:
String s = scan.next();
checkint = Integer.parseInt(s);
I have corrected it like below. I don't rely on exception, but check if the next Scanner input is int (using hasNextInt()). If not int, just consume Scanner token and wait for the next user input.
Looks like it is working, apart from 0 being inserted as a first array element, because you started indexing prompt from 1.
public class Herp {
//The main accesses the methods and uses them.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello and welcome!\n");
System.out.print("This program stores values into an array" + " and prints them.\n");
System.out.println("Please enter how many numbers would like to store:\n");
int arraysize = scan.nextInt();
int[] mainarray = new int[arraysize + 1];
int checkint = 0;
boolean notint = true;
int prompt = 1;
while (prompt < mainarray.length) {
while (notint) {
notint = false;
System.out.println("Please enter #" + prompt);
// check if int waits for us in Scanner
if (scan.hasNextInt()) {
checkint = scan.nextInt();
} else {
// if not, consume Scanner token
scan.next();
System.out.println("An integer is required."
+ "\n Input an integer please");
notint = true;
}
}
mainarray[prompt] = checkint;
System.out.println("Number has been added\n");
prompt++;
notint = true;
}
for (int i : mainarray) {
System.out.print(i + " ");
}
}
}

Categories