Java code, arithmetic and if/else statement issue [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hoping someone can give me a hand with this code. The beginning of the code you will see my psudo which states what I'm attempting to do. Only ever written in C++ before so the conversion is throwing me off some.
package correctFare;
/* create static variables for figures that will remain constant throughout program (fare,dollar value etc.)
*
* create variable that will be used to store the amount of money the user states is entered (entered amount must be 0=<x<=20
* Prompt user to enter the amount of money they are inserting which will be stored in the input var.
* note* remind user that amount must be divisable by .25 and no greater than 20.0
*
* subtract 2.25 from input, if the input-fare is not >= zero report error insufficient funds
* divide input by 0.25, if the number is not a whole number, int, report error and state that all values bust be multiples of 25 cents
*
* create open double variable as 'change'
* take input, subtract 2.25 and store new amount as change
*
* change is then divided by static variable ten, if zero continue to next step, else store amount as tenChange, change-(tenChange*10) continue to next step
* follow with dividing change by 5, same steps as prior
* repeat again with one
* lastly finish with quarters
*
* Prompt user with total cost of fare, amount entered and then tendered cash broken into each denomination
*/
import java.util.Scanner;
public class CTAFare {
/**
* #param args
*/
static double fare=2.25; //fare amount, remains easily accessible
static double quarter=0.25; //denomination amounts stored as static variables
static int oneDollar=1;
static int fiveDollar=5;
static int tenDollar=10;
static int twentyDollar=20;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner( System.in );
int max = 20;
int min = 0;
double inputAmount;
System.out.println("Please enter the amount of money you wish to insert:");
System.out.println("\n *Please note, this machine will accept bills no larger than $20 and must be divisible by $0.25.");
inputAmount = in.nextDouble();
if (min <= inputAmount <= max)
{
System.out.println("You entered: $"+ inputAmount);
}
else if (max < inputAmount < min)
{
System.out.println("The amount you entered is not acceptable.");
}
double change;
int tenChange;
int fiveChange;
int oneChange;
int quarterChange;
inputAmount-fare = change;
if (change/tenDollar > 0) {
change/tenDollar = tenChange;
change - (tenChange*10) = change;
}
else if (change/fiveDollar > 0) {
change/five = fiveChange;
change - (fiveChange * 5) = change;
}
else if (change/oneDollar > 0) {
change/onDollar = oneChange;
change - (oneChange * 1) = change;
}
else if (change/quarter > 0) {
change/quarter = quarterChange;
change - (quarter*0.25) = change;
}
System.out.println("You have purchased one fare at $"+ fare".\n");
System.out.println("Amount insterted: $"+ inputAmount "\n");
System.out.println("Change tendered: \n");
System.out.println("Ten Dollar Bills: "+ tenChange " \n");
System.out.println("Five Dollar Bills: "+ fiveChange " \n");
System.out.println("One Dollar Bills: "+ oneChange " \n");
System.out.println("Quarters: "+ quarterChange " \n");
}
}

Assignments in C++ are done from right to left, and I'm assuming that's similar for Java. Try changing your assignments...
change/five = fiveChange;
should be
fiveChange = change/five;
In this example, too, you haven't defined what five is anywhere. Unlike in Python, you need to define your variables before or when you use them.
Also, you might want to consider what each type is. I'm not sure int is the best choice in some of your circumstances. Try fixing your assignments and declarations, then see if your output is correct.

This could be a problem I noticed
if (min <= inputAmount <= max)
try using
if (min <= inputAmount && inputAmount <= max)
Here is another mistake
change/five = fiveChange;
You cant do this. Try following
double newFiveCHange = change/five ;
or interchang them like
fiveChange = change/five;
Following are useful links you can use.
1. Summary of Operators
2. The if-then and if-then-else Statements
3. Expressions, Statements, and Blocks

Just replace :
if (min <= inputAmount <= max)
by
if (min <= inputAmount && inputAmount <= max)
and replace :
else if (max < inputAmount < min)
by
else

Related

How can I make this code not return an infinite loop?

I think I have to use String goAgainResponse to make there not be an infinite loop but I don't know what the code for that would look like. I'm supposed to approximate pi by adding 4 - 4/3 + 4/5 - 4/7 + 4/9 etc. adding as many of these terms together as the number that I ask the user to put in.
int term;
int counter = 1;
double piCalc=0.0;
String goAgainResponse = null;
boolean goAgain = false;
Scanner kb = new Scanner(System.in);
/* NOTE you may not declare any additional variables */
do
{
System.out.println("This program will approximate Pi based on the following series:");
System.out.println("4 - 4/3 + 4/5 - 4/7 + 4/9 - ...");
System.out.println("Enter the term number to which you would like to approximate Pi");
term = kb.nextInt();
while(term <= 9)
{
System.out.print("Please enter a number greater than 9:");
term = kb.nextInt();
}
while(term > 9)
{
term += 1;
piCalc = 4/(2 * term - 1);
System.out.print(piCalc);
}
System.out.print("Would you like to try again (yes/no)? ");
}while(goAgain);
while(term <= 9)
{
System.out.print("Please enter a number greater than 9:");
term = kb.nextInt();
}
In this you are saying term should be greater than 9. But your in your second loop condition is term>9 and you are adding values in term, thats why the second loop is infinte
while(term > 9)
{
term += 1;
piCalc = 4/(2 * term - 1);
System.out.print(piCalc);
}
changing the condition of 2nd loop would resolve your problem. OR
consider term+=1 again.
Also as per #Scary Wombat, value of boolean doagain is never set
boolean goAgain = false;
This is never set to anything else, and the loop only loops while it is true

How can I use a formula in a for loop in java

I am a beginner java programmer, studying off basic youtube videos and overflow forums, and i came across a question on an textbook sheet that asked me to use a for loop program and print this table out as well as fill in each blank
Number Square Cube (n+1)/(2n-18)
______________________________________
1 # # #
2 # # #
3 # # #
4 # # #
5 # # #
I thought I should try it out to test myself. I came up with the following program that works perfectly for the Number, Square and Cube part of the table, but I don't understand how to generate the numbers using the given formula. The formula I initialized as a variable (double) doesn't print the actual results, and I honestly don't have a clue as to what to do. I'd rather a simple explanation than a complex one and simple changes to the code rather than complex. As I said I am a beginner, and many different methods may go right over my head. Thank you so much in advance (also an extra task asks that I print out the sums of each column. I don't know how to do that at all, and would like an explanation if possible, but wouldn't mind if I don't receive one)
int number;
int maxValue;
Scanner keyboard = new Scanner(System.in);
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();
System.out.println("Number\tSquare\tCube (n+1)/(2n-18)");
System.out.println("--------------------------------");
for (number = 1; number <= maxValue; number++) {
double formula = (number + 1) / (number * 2);
System.out.println(
number + "\t\t\t" + number * number + "\t\t\t" +
number * number * number + "\t\t\t" + formula);
}
Your formula should be:
double formula = (double)(number + 1) / (number * 2 - 18);
Two issues:
missing -18
the / is doing an integer division unless you cast at least one operand into a double
Oh! one more thing: when number==9, there is a division by zero. A double division gives you "Infinity" whereas an integer division throws an exception.
Your formula does not match the textbook. Try this:
System.out.println("Number\tSquare\tCube (n+1)/(2n-18)");
System.out.println("--------------------------------");
for (int number=1; number <= maxValue; number++) {
double square = Math.pow(number, 2);
double cube = Math.pow(number, 3);
double formula = (number + 1) / (number * 2 - 18);
System.out.println(number + "\t\t\t" + square + "\t\t\t" + cube + "\t\t\t" + formula);
}
Note: As pointed out by #MauricePerry an input of 9 would cause a divide by zero. Rather than try to catch this unchecked exception, I think you should control your input values so that this does not happen.
Your formula is not correct and you are missing few \t.
int number;
int maxValue;
Scanner keyboard = new Scanner(System.in);
System.out.println("how many numbers do you want the max value to be");
maxValue = keyboard.nextInt();
System.out.println("Number\t\tSquare\t\tCube \t\t(n+1)/(2n-18)");
System.out.println("-------------------------------------------------------");
for (number = 1; number <= maxValue; number++) {
double formula = (number + 1) / (number * 2 - 18);
System.out
.println(number + "\t\t" + number * number + "\t\t" + number * number * number + "\t\t" + formula);
}
I'm not sure which outputs are you getting, but it seems to me you're using integer division when trying to get the result of (n+1)/(2n-18).
Try using:
double decimalNumber = (double) number;
double formula = (decimalNumber + 1) / (decimalNumber * 2 - 18);

Lucky Sevens [Net Change Calculation] [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Whenever I execute the program the average change always is 0 and I do not understand why.
/*LuckySevens.java
Simulate the game of lucky sevens until all funds are depleted.
1) Rules:
roll two dice
if the sum equals 7, win $4, else lose $1
2) The inputs are:
the amount of money the user is prepared to lose
3) Computations:
use the random number generator to simulate rolling the dice
loop until the funds are depleted
count the number of rolls
keep track of the maximum amount
4) The outputs are:
the number of rolls it takes to deplete the funds
the maximum amount
the average net change after 100 rolls
*/
import java.util.Scanner;
import java.util.Random;
public class LuckySevens {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
Random generator = new Random();
int die1, die2, // two dice
dollars, // initial number of dollars (input)
countAtMax, // count when the maximum is achieved
count, // number of rolls to reach depletion
maxDollars, // maximum amount held by the gambler
averageWin, // the average net change after 100 rolls
initialDollars; // initial amount of money user has
// Request the input
System.out.print("How many dollars do you have? ");
dollars = reader.nextInt();
// Initialize variables
maxDollars = dollars;
initialDollars = dollars;
countAtMax = 0;
count = 0;
// Loop until the money is gone
while (dollars > 0){
count++;
// Roll the dice.
die1 = generator.nextInt (6) + 1; // 1-6
die2 = generator.nextInt (6) + 1; // 1-6
// Calculate the winnings or losses
if (die1 + die2 == 7)
dollars += 4;
else
dollars -= 1;
// If this is a new maximum, remember it
if (dollars > maxDollars){
maxDollars = dollars;
countAtMax = count;
}
/* TODO:FIX BELOW STATEMENT
it always returns influx as 0 */
if (count == 100) {
averageWin = ((maxDollars - initialDollars) / 100);
System.out.println ("In the first 100 rolls there an average money influx of " + averageWin + " per roll.") ;
}
}
// Display the results
System.out.println
("You went broke after " + count + " rolls.\n" +
"You should have quit after " + countAtMax +
" rolls when you had $" + maxDollars + ".");
}
}
Make averageWin as double variable.
Change calculation of average win as below
averageWin = ((double)maxDollars - (double)initialDollars) / 100;
I tried the following to get the correct answer.
Changed type of averageWin
double averageWin;
And then calculation formula to
averageWin = (maxDollars - dollars) / 100.0;
This will preserve the precision and give you the correct answer.

Loop input an input X amount of times

i am working on a Mock Test and i am struggling to create a loop that will cycle the input 12 times while adding each input to a sum.
Determines the average weight of a person over a particular year.
For each month, your algorithm should input the person's weight for that month (a positive real number). Your algorithm should loop,
repeating the input, until the input is positive.
Finally, your algorithm output the average weight.
After looking through lecture notes on Iteration Control Structures i have come up with this:
public static void main (String [] args)
{
double month, sum;
sum = 0;
for (month = 1; month <= 12; month++)
{
month = ConsoleInput.readDouble("Enter weight for each month");
sum += month;
}
System.out.println("Sum total is: " +sum);
}
Unfortunately all this does for me is repeat the input an infinite amount of times until i enter a number greater than 12.
I just want to make ConsoleInput cycle 12 times. Does anyone know the best way about this using while, do-while and for loops? I'm not allowed to use arrays, objects etc at this point in the course.
Any advice is appreciated cheers.
You can Possibly do the Following in order to make your Program Work.Just add one more variable monthweight and assign the user input
public static void main (String [] args)
{
double month, sum,monthweight;
sum = 0;
for (month = 1; month <= 12; month++)
{
monthweight = ConsoleInput.readDouble("Enter weight for each month");
if(monthweight > 0.0M)
{
sum += monthweight;
}
else
{
break;
}
}
System.out.println("Sum total is: " +sum);
}
You're using month in 2 ways, both to count to 12 and to receive the person's weight in. I think if you would assign ConsoleInput.readDouble(..) to another variable, and add that to the sum, your program will work better.

Better way of calculating sum of even ints

I'm trying to write a programme to prompt the user to input an int which is above or equal 2. From this input the programme must then calculate and print the sum of all the even integers between 2 and the entered int. It must also produce an error message if the inputted int is below 2. I've made a programme for it that works but am just wondering if you guys could find a better way of doing it? I'm sure there is but I can't quite seem to find a way that works!
Here's what I did:
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
int divnum = number / 2;
int divnum2 = divnum + 1;
int sumofeven = divnum * divnum2;
if(number >= 2)
System.out.println("The sum of the even integers between the number is "+
sumofeven);
else
System.out.println("Invalid number entered.");
}
}
Note: do not use this example in a real context, it's not effective. It just shows a more clean way of doing it.
// Check the input.
if (number >= 2)
System.out.println(sum(number));
}
// Will find the sum if the number is greater than 2.
int sum(int n) {
return n == 2 ? n - 2 : n % 2 == 0 ? n + sum(n - 2) : sum(n - 1);
}
Hope this helps. Oh, by the way, the method sum adds the numbers recursively.
Sorry, but I had to edit the answer a bit. There might still be room for improvement.
Why do it with a loop? You can actually calculate it out. Let X be the number they choose. Let N be the largest even number <= X. (N^2+2*N)/4 will be your answer.
Edit: just saw the answer above me. He is right. I gave the function I suppose.
Why use a loop at all? You are computing the sum of:
2 + 4 + ... n, where n is a positive even number.
This is a very simple arithmetic progression.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer which is above 2.");
int number = scan.nextInt();
if (number >= 2) {
int sumofeven = 0;
for (int i = 2; i <= number; i += 2) {
sumofeven += i;
}
System.out.println("The sum of the even integers between the number is " + sumofeven);
} else {
System.out.println("Invalid number entered.");
}
}

Categories

Resources