I am working a Collatz Conjecture Calculator that allows the user to enter the numbers into the calculator however, I am unsure why I am not meeting the specified output. The follwing are the test cases I am unable to meet, but I am unsure how I am wrong because it seems it prints as expected
TESTS FAILED...
java.lang.AssertionError:
Expected: a string containing "Enter the starting number:\nEnter the upper limit:\n90...45...136...68...34!\nOperation performed 4 times, and the resulting number is 34.\nDo you want to continue the calculations 5 more times? (yes/no)\n34...17...52...26...13!\nOperation performed 8 times, and the resulting number is 13.\nDo you want to continue the calculations 5 more times? (yes/no)\nDo you want to use the calculator again? (yes/no)"
but: was "Welcome to Collatz Conjecture Calculator!
Calculate with upper limit
Calculate until the end
Enter the starting number:
Enter the upper limit:
90...45...136...68...34!
Operation performed 4 times, and the resulting number is 34.
Do you want to continue the calculations 5 more times? (yes/no)
34...17...52...26...13!
Operation performed 8 times, and the resulting number is 13.
Do you want to continue the calculations 5 more times? (yes/no)
Operation performed 8 times, and the resulting number is 13.
Do you want to use the calculator again? (yes/no)
Thanks for using Collatz Conjecture Calculator!
"
java.lang.AssertionError:
Expected: a string containing "Welcome to Collatz Conjecture Calculator!\n1. Calculate with upper limit\n2. Calculate until the end\nEnter the starting number:\nEnter the upper limit:\n100...50...25...76...38!\nOperation performed 4 times, and the resulting number is 38.\nDo you want to continue the calculations 5 more times? (yes/no)\nDo you want to use the calculator again? (yes/no)\n1. Calculate with upper limit\n2. Calculate until the end\nEnter the starting number:\nEnter the upper limit:\n60...30...15...46...23...70...35!\nOperation performed 6 times, and the resulting number is 35.\nDo you want to continue the calculations 7 more times? (yes/no)\nDo you want to use the calculator again? (yes/no)\nThanks for using Collatz Conjecture Calculator!"
but: was "Welcome to Collatz Conjecture Calculator!
Calculate with upper limit
Calculate until the end
Enter the starting number:
Enter the upper limit:
100...50...25...76...38!
Operation performed 4 times, and the resulting number is 38.
Do you want to continue the calculations 5 more times? (yes/no)
Operation performed 4 times, and the resulting number is 38.
Do you want to use the calculator again? (yes/no)
Calculate with upper limit
Calculate until the end
Enter the starting number:
Enter the upper limit:
60...30...15...46...23...70...35!
Operation performed 6 times, and the resulting number is 35.
Do you want to continue the calculations 7 more times? (yes/no)
Operation performed 6 times, and the resulting number is 35.
Do you want to use the calculator again? (yes/no)
Thanks for using Collatz Conjecture Calculator!
"
END OF TEST FAILURES
{
public static void main(String[] args) {
String welcome = "Welcome to Collatz Conjecture Calculator!";
String optionOne = "1. Calculate with upper limit";
String optionTwo = "2. Calculate until the end";
String initialNumPrompt = "Enter the starting number:";
String upperLimitPrompt = "Enter the upper limit:";
String result = "Operation performed %d times, and the resulting number is %d.";
String unfinishedPrompt = "Do you want to continue the calculations %d more times? (yes/no)";
String againPrompt = "Do you want to use the calculator again? (yes/no)";
String farewellPrompt = "Thanks for using Collatz Conjecture Calculator!";
Scanner scanner = new Scanner(System.in);
String userChoice = "yes";
System.out.println(welcome);
while (userChoice.equals("yes")) {
System.out.println(optionOne);
System.out.println(optionTwo);
int option = scanner.nextInt();
scanner.nextLine();
while (option != 1 && option != 2) {
System.out.println(optionOne);
System.out.println(optionTwo);
option = scanner.nextInt();
scanner.nextLine();
}
System.out.println(initialNumPrompt);
int number = scanner.nextInt();
scanner.nextLine();
int counter = 0;
if (option == 1) {
System.out.println(upperLimitPrompt);
int limit = scanner.nextInt() - 1;
scanner.nextLine();
while (number != 1 && counter < limit) {
System.out.print(number + "...");
if (number % 2 == 0) {
number /= 2;
} else {
number = 3 * number + 1;
}
counter++;
}
if (number == 1) {
System.out.println("1!");
} else {
System.out.println(number + "!");
String continueCalculation = "yes";
while (continueCalculation.equals("yes") && number != 1) {
System.out.printf(result, counter, number);
System.out.printf(unfinishedPrompt, limit + 1);
continueCalculation = scanner.next();
if (continueCalculation.equals("yes")) {
int i = 0;
while (i < limit && number != 1) {
System.out.print(number + "...");
if (number % 2 == 0) {
number /= 2;
} else {
number = 3 * number + 1;
}
counter++;
i++;
}
if (number == 1) {
System.out.println("1!");
} else {
System.out.println(number + "!");
}
}
}
}
} else {
while (number != 1) {
System.out.print(number + "...");
if (number % 2 == 0) {
number /= 2;
} else {
number = 3 * number + 1;
}
counter++;
}
System.out.println("1!");
}
System.out.printf(result , counter, number);
System.out.println(againPrompt);
userChoice = scanner.next();
}
System.out.println(farewellPrompt);
}
}
I made sure that everything was printed on a new line, however you do not see that reflected in my code because it did not solve the problem
Related
I am having a problem with my program. When I compile and run my program everything runs great until it's time to display the guesses back to the user. when that happens the last guess always gets displayed as 0.
My assignment is to develop a program that simulates the high-low game. For each execution of the program, the game will generate a random number in the inclusive range of 1 to 100. The user will have up to 10 chances to guess the value. The program will keep track of all the user’s guesses in an array. For each guess, the program will tell the user if his/her guess was too high or too low. If the user is successful, the program will stop asking for guesses, display the list of guesses, and show a congratulatory message stating how many guesses he/she took. If the user does not guess the correct answer within 10 tries, the program will display the list of guesses and show him/her the correct value with a message stating that he/she was not successful. Regardless of the outcome, the program will give the user a chance to run the program again with a new random number.
This is what I have so far:
import java.util.Random;
import java.util.Scanner;
/**
*
* #author jose
*/
public class Assignment7
{
/*
*/
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int number;
String again = "y";
while (again.equalsIgnoreCase("y"))
{
int[] guesses = new int[10];
int tries = 0;
number = GetRandomNumber(1, 100);
System.out.println(number); // delete before submitting
int userGuess = GetUserGuess(1,100);
while (userGuess != number && tries < guesses.length - 1 )
{
guesses[tries] = userGuess;
LowOrHigh(number, userGuess);
userGuess = GetUserGuess(1, 100);
tries++;
}
if (tries != 10)
{
userGuess = guesses[tries];
tries++;
System.out.println("Congratulations! You were able to guess the correct number");
}
else
{
System.out.println("Sorry! You were not able to guess the correct number");
}
if (tries == 10)
{
System.out.println("Your guesses were incorrect");
System.out.print("You guessed: ");
for ( int i = 0; i < 10 ; i++)
{
System.out.print(guesses[i] + ", ");
}
System.out.println("The random number generated was " + number);
}
else
{
System.out.println("Well done! You were able to guess the "
+ "correct number in under 10 tries");
System.out.print("You guessed: ");
for ( int i = 0; i < tries; i++)
{
System.out.print(guesses[i] + " ");
}
System.out.println("The random number generated was "
+ number + ", it only took you " + tries + " tries.");
}
System.out.println("");
System.out.print("Do you wish to try again with a different "
+ "number? (Enter y or n ): ");
again = input.next();
System.out.println("");
}
}
/*
METHOD 1
Description
A method that generates the random number to be guessed returns the
random number to main. Two parameters are the two numbers needed to generate
the random number (1 and 100 in this case).
*/
public static int GetRandomNumber (int rangeLow, int rangeHigh)
{
Random gen = new Random();
int number;
number = gen.nextInt(rangeHigh) + rangeLow;
return number;
}
/*
METHOD 2
This method tells the user if the guess is too low or too high. It will have
2 parameters one for the random number and the second is the user guess.
*/
public static void LowOrHigh (int number, int userGuess )
{
if (userGuess > number )
{
System.out.println("The value that you guessed is too high, "
+"Try guessing a lower number. ");
System.out.println("");
}
else if (userGuess < number )
{
System.out.println("The value that you guessed is too low, "
+"Try guessing a higher number. ");
System.out.println("");
}
}
/*
METHOD 3
This method will get the user guess. It has 2 parameters which will be the
valid range the user should guess between (in this case 1 and 100). It will
return the users guess as an integer. This method should validate that the
users guess is between the two parameters.
*/
public static int GetUserGuess(int rangeLow, int rangeHigh)
{
Scanner scan = new Scanner(System.in);
int userGuess;
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
while (userGuess > rangeHigh || userGuess < rangeLow)
{
System.out.println("The number given was not within the range, Try again ");
System.out.println("");
System.out.print("Enter a number between " + rangeLow + " and " + rangeHigh + ": ");
userGuess = scan.nextInt();
}
return userGuess;
}
}
I'm sorry if its obvious im still pretty new to programming.
Whenever you store a guess, you always store it in guesses[tries], and then immediately afterwards, you increment tries. Your while condition then checks if tries is less than guess.length - 1.
More generally, to program you need to know how to debug. Debugging is generally the act of following along with the code and checking what it actually does vs. what you wanted it to do. You can use a debugger for this, alternatively, you can add a boatload of System.out statements to follow along.
Do that, and you'll find the error in your logic. I've already given you quite a sizable hint in the first paragraph ;)
what I am looking to do is create a program that will randomly pick an integer between 1 and 100. Then, ask the user to guess it. Loop until they do, and after each incorrect guess tell them if they are too high or too low. I want to use two different methods to validate their input. One to test whether it is a valid int, the other to test the range (1-100). This second will require another parameter for the high range value.
The problems I am having:
1. I do not understand why I have to enter a number multiple times before my while (guess != a) { is triggered.
Example from console :
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
6
higher!
2. how could I use my check methods and have them pertain to my while guess loop?
Example from console again:
`I am thinking of a number from 1 to 100 ... guess what it is? 10001
I am thinking of a number from 1 to 100 ... guess what it is? 10001
Error! Must be less than 100
I am thinking of a number from 1 to 100 ... guess what it is? 10001
100
lower!
10001
lower!`
{What I have full written currently}
package labbs;
import java.util.Scanner;
public class Lab12 {
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low)
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
if (num > 100)
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
return num;
}
public static double getDouble(Scanner input, String prompt) {
boolean OK;
double val=0;
do {
System.out.print(prompt);
OK = true;
try {
val = input.nextDouble();
}
catch(Exception e) {
OK = false;
System.out.println("Error! Invalid input. Must be a double value");
input.next();
}
}while(! OK);
return val;
}
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
double output, letscheck;
int count=0, guess=0;
int a=1 + (int) (Math.random() * 99);
letscheck = getDoubleGreaterThan(-0.9, keyboard,"I am thinking of a number from 1 to 100"
+ " ... guess what it is ?");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.println("lower!");
} else if (guess < a) {
System.out.println("higher!");
}
}
System.out.println("Congratulations. You guessed the number with "
+ count + " tries!");
}
}
1. Query: You have just missed bracket in getDoubleGreaterThan()method as after if statement block always working not on the basis of input so change your code like below:
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low){
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
}
if (num > 100){
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
}
return num;
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
Hi I am new to programming and have been assigned "Minimum Coins Program" for a class I am taking. I have finished the main code for it and it runs fine. But part of the parameters is that if the user enters a zero the program will exit, if not the program will continue looping. I have tried looking up answers but none have worked so far.
Here is what I have, but I can't seem to grasp looping. This is our first non flowchart assignment. Also if you have any suggestions on improving what I already have that would also be appreciated(this professor is a very harsh grader).
How can I get the program to exit through the user entering zero, and how can I keep the programming looping until the user enters zero. As of now the program just runs once and when I enter zero it lists the minimum amount of change
package mincoins;
import java.util.Scanner;
public class MinCoins
{
public static void main(String[] args)
{ //start code
//initialization
Scanner input = new Scanner(System.in); //create input class to get change data
int amount, quartercount = 0, dimecount = 0, nickelcount = 0, penniecount = 0;
amount = 1;
while (amount != 0)
{
System.out.println("Please Enter amount of change (1-99) or ZERO to EXIT");
System.out.println("");
amount = input.nextInt();
{
while (amount > 25)
{
amount = amount - 25;
quartercount++;
}
while (amount > 10)
{
amount = amount - 10;
dimecount++;
}
while (amount > 5)
{
amount = amount - 5;
nickelcount++;
}
System.out.println("");
System.out.println("Quarters: " + quartercount);
System.out.println("Dimes: " + dimecount);
System.out.println("Nickles: " + nickelcount);
System.out.println("Pennies: " + amount);
System.out.println("");
}
}
}//main
}//class
Your program (often) ends after 1 loop because your code reduces amount as it progresses, and if the number of pennies required is zero, the loop ends because amount is reduced to zero.
Try this:
while (true) {
// print and read amount
if (amount == 0)
break;
// rest of code
}
Why does the second while loop while (numberOfTries < 2) cancel both while loops? It runs perfect if there is no incorrect answer. But let's say I select 4 problems to be made, and I am only on the first problem. I give the incorrect answer 2 times so the program should say Incorrect two times and then give me a new question because while (numberOfTries < 2) should force it to break from that loop. But it doesn't, it just quits the whole thing. I know it has to be a logic issue, so what am I missing?
import java.util.Random;
import java.util.Scanner;
public class Howthe {
public static void main(String[] args) {
// Open Scanner
Scanner scan = new Scanner(System.in);
// Ask user to choose number of problems to be made.
// Can only choose 4, 9, or 16
System.out.print("Choose a number of problems to be made (4, 9, 16): ");
int userChoiceOfProblems = scan.nextInt();
// Ask user to choose a number between 0 and 12
System.out.print("\nChoose a number between 0 and 12: ");
int userNumberBetween0and12 = scan.nextInt();
// Ask user to choose between add/sub or multiply/divide
System.out.println("\nChoose to:"
+ "\n0: add/sub your chosen number"
+ " and the randomly generated number: "
+ "\n1: multiply/divide your chosen number"
+ " and the randomly generated number: ");
int userArithmeticChoice = scan.nextInt();
int counter = 0;
String equationString;
int equationAnswer;
int numberOfAnswersRight = 0;
int numberOfTries = 0;
int userAnswerToQuestion;
if (userArithmeticChoice == 0){
while (counter < userChoiceOfProblems){
// Create random number to decide if add or sub used.
// add is equal to 0 and sub is equal to 1
Random rand = new Random();
int randomNumberBetween0and1 = rand.nextInt(1) + 0;
// Create random number that is multiplied by userNumberBetween0and12
int randomNumberBetween0and12 = rand.nextInt(12) + 0;
// Add and increase counter by 1
if (randomNumberBetween0and1 == 0){
// If numberOfTries is more than 2, then display answer.
while (numberOfTries < 2){
// Compute the right answer (addition).
equationAnswer = userNumberBetween0and12 + randomNumberBetween0and12;
// Produce string of equation, then display string (addition).
equationString = userNumberBetween0and12 + " + "
+ randomNumberBetween0and12;
System.out.println(equationString);
userAnswerToQuestion = scan.nextInt();
// If answer is right, increase numberOfAnswersRight.
if (userAnswerToQuestion == equationAnswer){
numberOfAnswersRight++;
System.out.println("Correct!");
break;
}
// If answer is wrong, continue loop and increase numberOfTries
else if (userAnswerToQuestion != equationAnswer){
numberOfTries++;
System.out.println("Incorrect");
}
} // end of while (numberOfTries < 2 && !quit)
counter++;
}
} System.out.println("Yout got " + numberOfAnswersRight + " problem(s) right!");
}
}
}
numberOfTries is initialized outside of your loops. Once you try twice, it never gets set back to 0 which causes the loops to skip and finish on the next question because numberOfTries is already 2.
How do I round my numbers of output += Math.pow(baseUno, powernumber)+ " "; to the nearest whole number?
They always give me an output of, for example, 1.0 or 2.0. How do you round these so that they would simply result as 1 and 2?
import javax.swing.*;
import java.text.*;
import java.util.*;
public class level7Module1
{
public static void main(String[] args)
{
String base, power, output = " "; //user inputs, and the output variable
double baseUno, powerUno, basenum = 0, powernum = 0; //user inputs parsed so they can be used in mathematical equations
DecimalFormat noDigits = new DecimalFormat("0");
// oneDigit.format(variablename)
base = JOptionPane.showInputDialog(null,"Enter your prefered base, a number between 1 and 14: \nPress 'q' to quit."); //User input
if (base.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0); //quits
}
baseUno = Integer.parseInt(base);
// basenum = noDigits.format(baseUno);
if (baseUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (baseUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
//I chose 0 and 14 because on my monitor the combination of 14 and 14 filled up the entire screen, so I limited to things
//that would fit on my monitor :)
power = JOptionPane.showInputDialog(null, "How many numbers of this base would you like? Between 1 and 14 again, please.\nPress 'q' to quit.");
if (power.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0);
}
powerUno = Integer.parseInt(power);
// powernum = noDigits.format(powerUno);
if (powerUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (powerUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
for (int powernumber=0; powernumber!=powerUno; powernumber++) //Set the number of powers done to 0, then until it's "powernum" input, it keeps going.
{
output += Math.pow(baseUno, powernumber)+ " "; //Output is the basenum to the power of powernum plus a space, then repeats condition above.
}
JOptionPane.showMessageDialog(null,"Your numbers are: " + output); //Giving the users their outputs
}
}
To the simplest approach change this line :
JOptionPane.showMessageDialog(null,"Your numbers are: " + output);
to
JOptionPane.showMessageDialog(null,"Your numbers are: " + (int)output);
just type caste the result to int