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.
}
}
Related
I need to write a java program reading in an indefinite amount of numbers and saves them to a collection of numbers, until an (even number) is entered in by the user. I have tried with a while loop, that when a positive number is found in it it stops. But it is not really working. Here is codes I have tried:
public static void main(String[] args) {
int programInteger = 1;
int inputtedInteger;
while (programInteger < 2) {
System.out.println("Enter a number: "); //Asks user to input a number
Scanner in = new Scanner(System.in);
inputtedInteger = Scanner(in.nextLine);
if (inputtedInteger != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
inputtedInteger=in.nextInt();
}
else if (inputtedInteger % 2 == 0){
programInteger =+1;
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
}
/* if(inputtedInteger % 2 == 0) {
System.out.println("The number "+ inmatatTal +" you entered is an even number!");
}
else {
System.out.println("Enter a number?! ");
inputtedInteger = in.nextInt();
}
Fixing a few things in the logic of the loop should work:
int inputtedInteger = 0;
Scanner in = new Scanner(System.in);
while (inputtedInteger < 1) {
System.out.println("Enter a number: "); //Asks user to input a number
inputtedInteger = in.nextInt();
if (inputtedInteger % 2 != 0) {
System.out.println("The number "+ inputtedInteger +" that you inputted is not an even number, try again: ");
}
else if (inputtedInteger % 2 == 0){
System.out.println("The number "+inputtedInteger+" that you entered is an even number!");
}
}
I would setup an outline for the code like this:
setup Scanner, create collection
while true:
userInput = scanner.nextInt()
if userInput > 0: break
collection.add(userInput)
print('user entered', collection.length(), 'numbers.')
Hope that helps. I'll leave you to fill this using actual Java syntax.
I wrote a comment on the OP on why your structure is failing to solve the issue at hand.
I want to give the user a choice to quit the program while the program is running whenever they feel like it. E.g. Press Q and ENTER at anytime to quit and end program.
I have a try and catch method but whenever I press Q and ENTER, it just displays whats in the catch part.
Here is the code:
public static void partB() {
//Code for partB goes here.
//Continues on with partA but with few changes
/* The number of multiplication problems should not be fixed. Instead,
the program should keep posing new multiplication problems until the user decides to quit by entering the letter "q".
The program should be able to deal with invalid input by the user.
It should ignore such input and restate the current multiplication problem.
*/
//Uses the imported Random function.
Random num = new Random();
//Initialises the minimum and maximum numbers.
int minNumber = 10; //Minimum number to start random
int maxNumber = 20; //Maximum number to start random
int counter = 0; //Counts the number of questions answered.
int correctAnswers = 0; //Counts the number of correct answers given.
final int numberOfQuestions = 0;
while(numberOfQuestions >= 0) {
//Generates a random integer between 10 and 20.
int randInt1 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Repeats for the 2nd integer to get the product of the two numbers.
int randInt2 = (num.nextInt(maxNumber - minNumber) + minNumber);
//Initialise the Scanner function.
Scanner input = new Scanner(System.in);
//Output the Question.
System.out.println("What is " + randInt1 + " X " + randInt2 + "?" + " " + "(Press 'q' and ENTER to quit)");
//Waits for user input.
try {
int userInput = input.nextInt();
String quit = input.nextLine();
//If user input is 'q', quit program.
if(quit.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int answer = randInt1 * randInt2;
//Checks if the users input is correct.
if (answer == userInput) {
System.out.println("That is correct!");
correctAnswers++;
}
else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch(InputMismatchException e) {
System.out.println("You have entered something other than an integer or 'q'! Please try again with a different question!");
}
}
}
If you want to accept both a number and a letter, it is better to use nextLine(). First you check for q, and then parse to number, as follows (note that parseInt will throw a NumberFormatException):
try {
String userInput = input.nextLine();
// If user input is 'q', quit program.
if (userInput.equalsIgnoreCase("q")) {
System.out.println("Exiting...");
System.exit(0);
} else {
int userAnswer = Integer.parseInt(userInput);
int answer = randInt1 * randInt2;
// Checks if the users input is correct.
if (answer == userAnswer) {
System.out.println("That is correct!");
correctAnswers++;
} else {
System.out.println("That is incorrect! " + "The correct answer should be " + answer);
counter++;
}
}
} catch (NumberFormatException e) {
System.out.println(
"You have entered something other than an integer or 'q'! Please try again with a different question!");
}
So I wrote a java code for a numbers guessing game. The entire thing is pretty much done. It works by choosing a random number then asking the user for console inputs and then saying whether that is higher or lower than the random number. Once you guess it, it then asks if you want to play again. When you finally say no to this (be it one game or several) it prints out your Overall results including total games, total guesses, avg guesses/game and your best game. I have everything worked out except I cant figure out how to make it print your overall best game.
import java.util.*; //so I can use scanner
public class GuessingGame {
public static void main(String[] args) {
Random rand = new Random ();
int max = 100;
Scanner input = new Scanner(System.in);
int guess;
boolean play = true;
int totalGames = 0;
int totalGuesses = 0;
System.out.println("Can you guess the word?");
System.out.println("I am sure you cannot guess!");
System.out.println("Go ahead and try!");
System.out.println();
while (play) {
System.out.println("I'm thinking of a number between 1 and " + max + "...");
int numberToGuess = rand.nextInt(max) + 1;
int numberOfTries = 0;
boolean win = false;
while (!win) {
System.out.print("Your guess? ");
guess = input.nextInt();
numberOfTries++;
if (guess == numberToGuess) {
win = true;
} else if (guess > numberToGuess) {
System.out.println("It's lower.");
} else if (guess < numberToGuess) {
System.out.println("It's higher.");
}
input.nextLine();
}
if (numberOfTries == 1) {
System.out.println("You got it right in " + numberOfTries + " guess!");
} else {
System.out.println("You got it right in " + numberOfTries + " guesses!");
}
totalGames++;
totalGuesses+= numberOfTries;
System.out.print("Do you want to play again? ");
String answer = input.nextLine();
char firstLetter = answer.charAt(0);
if (firstLetter == 'y' || firstLetter == 'Y') {
play = true;
} else {
play = false;
}
System.out.println();
}
System.out.println("Overall results:");
System.out.println("Total games = " + totalGames);
System.out.println("Total guesses = " + totalGuesses);
System.out.println("Guesses/game = " + totalGuesses/totalGames);
System.out.println("Best game = ");
}
}
In order to get the best game you need a keep track of the best best after each game, such as a variable that checks it there is a new best game after each game.
Keep track of the best score, which is the lowest number of guesses.
int bestGame = Integer.MAX_VALUE; // at the top
bestGame = Math.min(bestGame, numberOfTries); // at the end of your inner while loop
The worst possible score is the highest number of guesses, which is limited by Integer.MAX_VALUE, so you start there.
By the best game u mean minimum number of tries needed to answer is the best game.
/* int mintries,bestgame,gamenumber=0;
bestgamenumber=0;mintreies=Integer.MAX_VALUE:*/
Add the above lines above your while(play)
gamenumber++;
/*if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
betgame=gamenumber;
}*/
Add the if condition just before closing while(play).
So it will be like
int mintries;
mintreies=Integer.MAX_VALUE:
int gamenumber=0;
int bestgamenumber=0//if you want to print the which game is the best game(!st,2nd,3rd..) ;
while(play)
{
// do all your stuff
gamenumber++;
if(mintries>numberOfTries)
{
mintries=numberOfTries;//update mintries
bestgamenumber=gamenumber;
}
}
}
System.out.println("Game number +bestgamenumber+"was the best game with"+ mintries+"tries);
I am considering that you want to print which game (1st,2nd,3rd)is best and minimum tries made to guess the best game.Correct me if i am wrong.
To fit into the code you have already written, You could
Create a new 'global' variable, for example int bestGame = Integer.MAX_VALUE;.
Whenever the user is done with a game do a check if the current numberOfGuesses is smaller than the current bestGame, and if it is, then overwrite bestGame with the current numberOfGuesses.
At the end, you simply need to output bestGame.
So I'm working on a copy of a simple Dice game that was an example from the Maxwell Sanchez YouTube JAVA on Eclipse tutorials. What I started playing around with is simple ways to implement a text based menu of sorts.
What I'm trying to accomplish is a Y or N input method of either restarting the program, or killing it. I'm a total noob, coming here after a tiny bit of Arduino. I'm liking JAVA but there are many things I don't understand.
My problem right now is, everything appears to work so far, except that if you get to the end and type N to quit, It requires 2 inputs of N to actually execute the else if statement. Is that something that is a bug? Or am I just mis-programing what I'm trying to accomplish.
import java.util.*;
public class diceGame
{
static int money;
static Scanner in = new Scanner(System.in);
static Random random = new Random();
static String userName;
static String tryAgain;
public static void main(String[] args)
{
money = 1000;
System.out.println("Welcome to this simple dice game! " +
"Please enter your name.");
String userName = in.nextLine();
System.out.println("Hey " + userName + ".");
rollDice();
}
public static void rollDice()
{
System.out.println("You have " + money + " coins!");
System.out.println("Please select a number (1-6) to bet on!");
int betRoll = in.nextInt();
System.out.println("Please place your bet!");
int betMoney = in.nextInt();
while (betMoney > money)
{
System.out.println("You don't have enough coins... you only " +
"have " + money + "coins.");
System.out.println("Please place a realistic bet!");
betMoney = in.nextInt();
}
int dice;
dice = random.nextInt(6)+1;
if (betRoll == dice)
{
System.out.println("You Win!");
money+=betMoney*6;
System.out.println("You have " + money + " coins.");
}
else
{
System.out.println("Snap! You lost your coins!");
money-=betMoney;
System.out.println("You have " + money + " coins.");
}
if (money <= 0)
{
System.out.println("You've lost all yer coins!");
System.out.println("Play again?" + " Type y or n");
if (in.next().equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (in.next().equalsIgnoreCase("n"))
{
System.out.println("Maybe next time...");
System.exit(0);
}
else
{
System.out.println("Invalid character");
}
}
else
{
rollDice();
}
}
}
Store the input in a variable, and compare it... or you'll have to input twice.
String choice = in.next();
if (choice.equalsIgnoreCase("y"))
{
System.out.println("Maybe you'll win this time!");
money = 1000;
rollDice();
}
else if (choice.equalsIgnoreCase("n")) // <-- not in.next()
Every time you call in.next() you read user input.
if (in.next().equalsIgnoreCase("y"))
else if (in.next().equalsIgnoreCase("n"))
In this code, you are calling in.next() twice, once for each condition, so it will read two inputs.
You need to separate the reading from the comparison.
String input = in.next();
if (input.equalsIgnoreCase("y"))
else if (input.equalsIgnoreCase("n"))
this one just is hurting my brain. http://programmingbydoing.com/a/adding-values-in-a-loop.html
Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end.
what ive got so far:
Scanner keyboard = new Scanner(System.in);
System.out.println("i will add");
System.out.print("number: ");
int guess = keyboard.nextInt();
System.out.print("number: ");
int guess2 = keyboard.nextInt();
while(guess != 0 && guess2 != 0)
{
int sum = guess + guess2;
System.out.println("the total so far is " + sum);
System.out.print("number: ");
guess = keyboard.nextInt();
System.out.print("number: ");
guess2 = keyboard.nextInt();
System.out.println("the total so far is " + sum);
}
//System.out.println("the total so far is " + (guess + guess2));
}
Declare the int sum variable outside of the while loop and only have one guess = keyboard.nextInt() inside the loop. Add the user's guess to the sum in the loop as well.
Then after the loop output the user's sum.
I.e.:
int sum;
while(guess != 0)
{
guess = keyboard.nextInt();
sum += guess;
}
System.out.println("Total: " + sum");
Edit: also remove the guess2 variable, as you will no longer need it.
The code will be as below :
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int input = 0;
int total = 0;
System.out.println("Start entering the number");
while((input=keyboard.nextInt()) != 0)
{
total = input + total;
}
System.out.println("The program exist because 0 is entered and sum is "+total);
}
Programming by Doing :)
int x = 0;
int sum = 0;
System.out.println("I will add up the numbers you give me.");
System.out.print("Number: ");
x = keyboard.nextInt();
while (x != 0) {
sum = x + sum;
System.out.println("The total so far is " + sum + ".");
System.out.print("Number: ");
x = keyboard.nextInt();
}
System.out.println("\nThe total is " + sum + ".");
import java.util.Scanner;
public class AddingInLoop {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number, total = 0;
System.out.print("Enter a number\n> ");
number = keyboard.nextInt();
total += number;
while (number != 0) {
System.out.print("Enter another number\n> ");
number = keyboard.nextInt();
total += number;
}
System.out.println("The total is " + total + ".");
}
}
You first prompt the user to enter a number. Then you store that number into total (total += number OR total = total + number). Then, if the number entered wasn't 0, the while loop executes. Every time the user enters a nonzero number, that number is stored in total ( the value in total is getting bigger) and the while loops asks for another number. If and when a user enters 0, the while loop breaks and the program displays the value inside total. :D I myself am a beginner and had a bit of an issue with the logic before figuring it out. Happy coding!