Java do loop repeat until valid entry - java

I'm creating a Java project using a do-while loop to get a number from the user between 5 and 15. After this, I will create a square and triangle using the number the user entered.
I'm currently stuck on making my question repeat. After I run the program it runs fine until I input a number the second time the user is prompted to enter a number. It won't print if the number is invalid or not.
I tried moving the second "Enter a number..." inside of the do-loop but that just printed with the "Sorry, invalid" prompt. I did something similar with a case statement inside a while loop and it ran fine but I'm having difficulty with the do loop.
Can someone point me in the right direction?
import java.util.Scanner;
public class doLoop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
int minimum = 5;
int maximum = 15;
System.out.print("Enter a number between " + minimum + " and " + maximum + ":" );
do {
number = input.nextInt();
if (number >= minimum && number <= 15)
break;
else
System.out.print("Sorry, invalid");
break;
} while (false);
System.out.print("\nEnter a number between " + minimum + " and " + maximum + ":" );
number = input.nextInt();
}
}

In general, use break inside a while loop is considered a bad practice. You should have something like this
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
int minimum = 5;
int maximum = 15;
do{
System.out.print("Enter a number between" + " " + minimum + " " + "and" + " " + maximum + ":" );
number = input.nextInt();
if (number < minimum || number > maximum)
System.out.print("Sorry, invalid");
} while (number < minimum || number > maximum);
}

There is a logical error in your code in the placement of your break and scanner input. If you really want to stay true to what you have, I find it much simpler to just add a boolean check instead of using a break. Below you can see I also put final so that way you know, and is a best practice that, that variable should not be altered or tampered with in code. I added a boolean since you wanted to check the do while for false, then we set it to true if it passes the if statement you made.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number;
boolean check = false;
// Final, because they are constant through-out the program
final int minimum = 5;
final int maximum = 15;
do {
System.out.print("Enter a number between " + minimum + " and " + maximum + ":" );
number = input.nextInt();
if (number >= minimum && number <= maximum)
check = true;
else
System.out.println("Sorry, invalid");
break;
} while (check);
}

Related

How can I ask the user to re-enter their choice?

I know how to display an Error message if the user enters a number below 10 or higher than 999 but how can I code to make sure the program doesn't end after the users enter a number below 10 or higher than 999 and give them a second chance to enter their valid input over and over again until they give a correct input.
import java.util.Scanner;
public class Ex1{
public static void main(String args[]){
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter an integer between 10 and 999: ");
int number = input.nextInt();
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
}
You will need to use a loop, which basically, well, loops around your code until a certain condition is met.
A simple way to do this is with a do/while loop. For the example below, I will use what's called an "infinite loop." That is, it will continue to loop forever unless something breaks it up.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start a loop that will continue until the user enters a number between 1 and 10
while (true) {
System.out.println("Please enter a number between 1 - 10:");
num = scanner.nextInt();
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
} else {
// Exit the while loop, since we have a valid number
break;
}
}
System.out.println("Number entered is " + num);
}
}
Another method, as suggested by MadProgrammer, is to use a do/while loop. For this example, I've also added some validation to ensure the user enters a valid integer, thus avoiding some Exceptions:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
// Start the loop
do {
System.out.println("Please enter a number between 1 - 10:");
try {
// Attempt to capture the integer entered by the user. If the entry was not numeric, show
// an appropriate error message.
num = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error: Please enter only numeric characters!");
num = -1;
// Skip the rest of the loop and return to the beginning
continue;
}
// We have a valid integer input; let's make sure it's within the range we wanted.
if (num < 1 || num > 10) {
System.out.println("Error: Number is not between 1 and 10!\n");
}
// Keep repeating this code until the user enters a number between 1 and 10
} while (num < 1 || num > 10);
System.out.println("Number entered is " + num);
}
}
Try this, i just include the while loop in your code it will work fine.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = askInput(input);
while(number<10 || number>999) {
System.out.println("Sorry Try again !");
number = askInput(input);
}
int lastDigit = number % 10;
int remainingNumber = number / 10;
int secondLastDigit = remainingNumber % 10;
remainingNumber = remainingNumber / 10;
int thirdLastDigit = remainingNumber % 10;
int sum = lastDigit + secondLastDigit + thirdLastDigit;
if(number<10 || number>999){
System.out.println("Error!: ");
}else{
System.out.println("The sum of all digits in " +number + " is " + sum);
}
}
private static int askInput(Scanner input) {
int number = input.nextInt();
return number;
}

Letter guessing game Java

I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!
I want the user to try and guess the letter and not the number, but i cannot workout how to do this!
(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
Any help would be greatly appreciated! And i can display my code if it is needed
public class Stack {
public static void main(String[] args) {
Random rand = new Random(); //This is were the computer selects the Target
int guess;
int numGuesses = 0;
int Target;
String userName;
String playagain;
boolean play = true;
int session = 0;
int sessions = 0;
int bestScore = 0;
Scanner consoleIn = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
userName = name.nextLine();
System.out.println("Hello " + userName + " :) Welcome to the game!\n");
while (play = true) {
session++;
Target = rand.nextInt(26) + 1;
System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have
do {
guess = consoleIn.nextInt();
numGuesses++;
if (guess > 26)
System.out.println("Error! Above MAXIMUM range");
else if (guess <= 0)
System.out.println("Error! Below MINIMUM range");
else if (guess > Target)
System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
else if (guess < Target)
System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
} while (guess != Target && numGuesses < 5);
if (guess == Target) {
System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
sessions++;
} else {
System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!"); //This tells the player that they failed to find the number and then tells them what the correct answer
}
{
Scanner answer = new Scanner(System.in);
System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
playagain = answer.nextLine();
if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
play = true;
numGuesses = 0;
} else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
play = false;
System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
System.out.println("You had " + session + " Goes");
System.out.println("The number of times you guessed correctly: " + sessions + "");
break;
}
}
}
}
}
use arrays of characters
char[] chars = ['A','B','C'...];
and use the random numbers to map to each character
char targetLetter = chars[r.nextInt(26)];
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Guess the Letter");
String myLetter=scan.nextLine();
//get the letter of myLetter variable then convert to Uppercase
char enteredLetter=Character.toUpperCase(myLetter.charAt(0));
//26 only because the characters array starts with index 0
char[] characters ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//I had created a parrallel array symbolizing int value of each letter
int[] range={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
//this variable convert user input to one of the array element of range
int userInputToInt=0;
//this variable is for knowing what int[] range array element must the value of userInputToInt fall
int userInputControlLoop=0;
char randomLetter=characters[(int)(Math.random()*26)];
// get the random input of computer convert it to int
int computerInputToInt=0;
//this loop is for getting the int value of randomLetter input by the computer
for(int i=0;i<characters.length;++i)
{
if(randomLetter==characters[i])
{
computerInputToInt=range[i];
}
}
//this loop is for getting the int value of user inputted letter
for(char i:characters)
{
if(enteredLetter==i)
{
userInputToInt=range[userInputControlLoop];
}
++userInputControlLoop;
}
//test the entered letter of user
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if greater than computer input
else if(userInputToInt>computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too high");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if lesser than computer input
else if(userInputToInt<computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too low");
System.out.println("The letter is:"+randomLetter);
}
}
Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding A-Z:
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
...
int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) {
System.out.println("Correct!");
} else {
System.out.println("Guess again!")
}
You can implement it in this approach :
1- Create a String alphabet with the characters that you want.
2- declare the size of alphabet as n variable which will control the random generator range.
3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.
program code will be :
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int n = alphabet.length();
Random r = new Random();
System.out.println(alphabet.charAt(r.nextInt(n)));
hope will help solve your problem.
public class Picnic1 {
// RULE 0: This code is provided as a working example.
// This rule tests for whether a word starts with the letter 'b' (allowed to the picnic).
public static boolean rule0(char[] array) {
if (array[0] == 'b') {
return true;
}
else {
return false;
}
// itemMessage:
// Return message about whether a particular item is allowed to the picnic.
public static String item ( double[] a){
// This code works, providing output like these examples:
// "banana: true"
// "collie: false"
// It needs to be replaced with a more suitable output.
// Instead it should return, for example:
// "Yes, you can bring a banana to the picnic."
// "No, you cannot bring a collie to the picnic."
if (a[0] == 'b') {
System.out.println("Yes, you can bring a" + 'a' + "to the picnic");
}
else if (a[0] != 'b') {
System.out.print("No, you can not bring a " + 'a' + "to the picnic");
}
}
}
}

Basic Java program tune up assistance

My program asks the user for their name, then asks for a number of shuffles of 3 random numbers.
When one of the shuffles adds to the desired number (which is 31) the shuffle stops. I need to happen that the program only reads the LAST SHUFFLE. E.g.
how many shuffles do you want: 3
10 + 11 + 10 = 31 congrats you are the winner!!
The current output is:
9 + 6 + 8
8 + 10 + 12
7 + 9 + 11
I need assistance in making sure the user cannot put non alphabetical characters in their name. I also need the ability to be able to print out how many shuffles the user had before the numbers were printed out.
Here is my code,
`import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
//enter their first name
String first_name;
System.out.print("Enter Your First Name: ");
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
last_name = user_input.next();
//full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
//this is the buffer that resets if the user types a letter instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out
.println(" You will be given a hand of 3 random numbers between 7-13"
+ "\n you will be drawn a the number of shuffles as you entered above ");
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win.");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = "
+ (num1 + num2 + num3));
// adding the numbers together
if (num1 + num2 + num3 == 31) {
isWinner = true;
System.out
.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
}
if (!isWinner)
System.out.println("Better Luck Next Time");
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// if pressed y or yes the program will run again with the same number of shuffles entered from before
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}`
Arraylist numberStore = new Arraylist();
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
isWinner = true;
System.out
.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
to make sure that only the last shuffle can get read as a winner or loser.
Because you are initializing your num1, num 2... variables inside of your for loop then those variables are scoped to that for loop. I would suggest that if you want to make sure that only one set of numbers can be judged then you move the scope out of the loop. Adding the totals to an array would then allow you to choose as many as you want to judge.
When it comes to sterilizing your inputs you can use util.Scanner to do most of it for you with a little knowledge of regex:
while (!scan.hasNext("[A-Za-z]+")) {
System.out.println("Nope, that's not it!");
sc.next();
}
This will stop your scanner allowing any none alphabetical char's being entered, you can read more about Regex with this tool

ArrayList If Loop not working properly: JAVA

I have a program that asks the user their name etc. Then it asks how many times do you want the numbers to loop (so my program generates 3 random numbers between 7 and 13 and if it adds up to 31 they are the winner) and my issue is that I only want the last printed number to count towards if the player wins or looses, the other numbers are just for show or tease i guess. the problem is that regardless towards if the player wins or looses, the losing statement always prints out. Below is my entire code.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;
import java.util.Random;
public class StringVariables {
public static void main(String[] args) throws NumberFormatException,
IOException {
// user inputs their name in this section
Scanner user_input = new Scanner(System.in);
//enter their first name
String first_name;
System.out.print("Enter Your First Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
//enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while
(!user_input.hasNext("[A-Za-z]+")) {
System.out.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
//full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
//this is the buffer that resets if the user types a letter instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out
.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13" );
delay(2000);
System.out
.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
Arraylist numberStore = new Arraylist();
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
// if pressed y or yes the program will run again with the same number of shuffles entered from before
user_input.close();
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
}
int lastNumber = (numberStore.size() - 1);
if (lastNumber == 31) {
you probably want something like
int lastNumber = numberStore.get(numberStore.size() - 1);
if (lastNumber == 31) {
to verify that is the error try to change that line to
int lastNumber = num1 + num2 + num3;
Edit based on further messages:
Looks like what you really want is this:
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
System.out.println(num1 + " + " + num2 + " + " + num3 + " = " + (num1 + num2 + num3));
numberStore.add(num1 + num2 + num3);
int lastNumber = num1 + num2 + num3;
boolean lastShuffle = (i == (numShuffles - 1));
if (lastShuffle) {
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
} else {
System.out.println("Better Luck Next Time");
}
}
}
// play again prompt
System.out
.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
Just a general suggestion: avoid to use break if possible, it makes control flow hard to follow and is not a good programming practice.
Several points to make here. One, your code is quite messy and hard to read. It's helpful when you're asking for help (and in general anyway) to properly indent your code. This is good practice and if you do other languages like Python can help you out a lot. Also, why do a check for !isWinner? Scrap the isWinner variable altogether and just check for the number equalling 31 and then have an else statement for the losing statement. Like this:
if (lastNumber == 31) {
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
//if you loose every shuffle
}
else {
System.out.println("Better Luck Next Time");
}
Also, take some steps to find the error. Print out each number as you get it, and use
int lastNumber = num1 + num2 + num3;
instead of
int lastNumber = (numberStore.size() - 1);
Also for anybody else compiling this, it's ArrayList and not Arraylist... just a little slip.
Sorry, I may have to say that your codes are a kind of mess up. a small factory with the solution you ask, hope it can be a little help to you
public static void main(String[] args) throws NumberFormatException,
IOException {
Scanner user_input = new Scanner(System.in);
String full_name = registeGamePlayer(user_input);
int numShuffles = initGame(user_input);
showTheGameInfo(full_name, numShuffles);
runningGame(user_input, numShuffles);
user_input.close();
}
/**
* #param user_input
* #param numShuffles
*/
private static void runningGame(Scanner user_input, int numShuffles) {
// random number generator
Random random = new Random();
while (true) {
// the shuffle loop
boolean isWinner = false;
for (int i = 0; i < numShuffles; i++) {
int num1 = 7 + random.nextInt(7);
int num2 = 7 + random.nextInt(7);
int num3 = 7 + random.nextInt(7);
int amount = num1 + num2 + num3;
System.out.printf("%d + %d + %d = %d \n", num1,num2,num3,amount);
if (amount == 31) {
isWinner = true;
System.out.println("Congratulations !! You are the Lucky Winner !!!!");
break;
// if you loose every shuffle
}
}
if (!isWinner) {
System.out.println("Better Luck Next Time");
}
// play again prompt
System.out.println(" Do you want to play again? (If you do enter y or yes) \n To exit press any other key ");
String input = user_input.next();
if (!"y".equalsIgnoreCase(input) && !"yes".equalsIgnoreCase(input)) {
break;
}
}
}
/**
* #param full_name
* #param numShuffles
*/
private static void showTheGameInfo(String full_name, int numShuffles) {
// printing 25 blank lines
for (int i = 0; i < 25; i++)
System.out.println(" ");
System.out.println("User playing: " + full_name);
System.out.println("Number of times shuffled: " + numShuffles);
System.out.println("Your lucky numbers are...");
}
// delay field
public static void delay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException exp) {
// delay field
}
}
private static String registeGamePlayer(Scanner user_input){
String first_name;
System.out.print("Enter Your First Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
first_name = user_input.next();
// enter their last name
String last_name;
System.out.print("Enter Your Last Name: ");
while (!user_input.hasNext("[A-Za-z]+")) {
System.out
.println("Please only enter alphabet characters. Try again.");
user_input.next();
}
last_name = user_input.next();
// full name printed together
String full_name;
full_name = first_name + " " + last_name;
System.out.println(full_name + " Is Now Playing");
return full_name;
}
private static int initGame(Scanner user_input){
// this is the shuffle portion as well as something to see if a number
int numShuffles = -1;
while (numShuffles < 0) {
System.out.println("How many times do you want the numbers shuffled? ");
try {
numShuffles = user_input.nextInt();
} catch (InputMismatchException inputException) {
System.out.print("Please enter a valid number. \n");
// this is the buffer that resets if the user types a letter
// instead of a number, or any other character
user_input.next();
}
}
// here is going to be the loop for shuffles
// we are now going to generate their random number and add a delay
// after completing their name fields
delay(3000);
System.out.println(" You will be given " + numShuffles + " hand(s) of 3 random numbers between 7-13");
delay(2000);
System.out.println(" Then, the computer will add the random numbers and if it is equal to 31, you win!");
/*
* end of explanation of the game, next i will create a new screen with
* the user's name and numbers
*/
delay(4000);
return numShuffles;
}

Allow the user to continue entering numbers until they choose to quit

This program's objective is to calculate the n-th Fibonacci number. How do I allow the user to continue entering numbers until they choose to quit? Thanks.
public class FibonacciNUmbers
{
public static int calcFibNum(int x)
{
if (x == 0)
return 0;
else if (x == 1)
return 1;
else
return calcFibNum(x-1) + calcFibNum(x-2);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("What number would you like to find the Fibonacci number for?");
int x = in.nextInt();
System.out.println("The Fibonacci number of " + x + " is " + calcFibNum(x));
System.out.println("Would you like to find the Fibonaci number of another number?");
String answer = in.next();
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println();
}
}
}
By the way your code prints all the Fibonacci numbers up to n and not the nth number.Below is just an example of how to keep entering input from Scanner. Use that to build upon what you want to do:
int num = 0;
while (in.hasNextInt()) {
num = in.nextInt();
}
Happy coding!
//start your while loop here
while (true)
{
System.out.println("Would you like to find the Fibonacci number of another number?");
String answer = in.next();
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println("Thanks for playing");
break; // ends the while loop.
}
}
For loops are used when you can count things or have a set of things. While loops are used when you're not sure how long it might go on for, or if you want it to continue until some event occurs (user pressing a certain letter for example)
Slight variation of the above that is probly a bit more elegant:
String answer = "Y";
//start your while loop here
while (answer.equals("Y")) {
System.out.println("Would you like to find the Fibonacci number of another number?");
answer = in.next(); //declare your variable answer outside the loop so you can use it in the evaluation of how many times to do the loop.
if (answer.equalsIgnoreCase("Y"));
{
System.out.println("What number would you like to find the Fibonacci number for?");
x = in.nextInt();
System.out.println("The Fibonacci number for " + x + " is " + calcFibNum(x));
}
else
{
System.out.println("Thanks for playing");
// no need to break out.
}
}

Categories