For loop error -> if statement not producing output in - java

This is some work which I'd much rather figure out myself so could you please not give the answer right out if possible but maybe point me into the right direction to why I am receiving the error from the loop output and why the IF statement is not producing the output.
I have to allow a user input for the 'Recommended maximum staff wage' and then read text from a file of different shop units to work out the staff wages and total staff cost per shop units.
Here is the text I have to read
Unit One
4
32 8
38 6
38 6
16 7
Unit Two
0
Unit Three
2
36 7
36 7
Unit Four
6
32 6.5
32 6.5
36 6.5
36 6.5
38 6.5
38 6.5
...continued up to 9 shop units.
This is my code:
public class Recursion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count =0;
int n = 1;
int t=0;
int triangularNumber =0;
while (n<Integer.MAX_VALUE)
{
t = isTriangularNumber(n,count,triangularNumber);
triangularNumber=0;
int starNumber= ((6*n)*(n-1)) + 1;
if (starNumber ==t)
{
System.out.println(t);
}
n++;
}
if (n==Integer.MAX_VALUE)
{
System.exit(0);
}
}
public static int isTriangularNumber(int n, int count, int triangularNumber)
{
triangularNumber =triangularNumber + (n-(n-count));
if (count<=n)
{
return isTriangularNumber(n,(count++), triangularNumber);
}
else return triangularNumber;
}
}
The printouts for the shop units are fine, but it produces an error after the output, and the output from the if-statement isn't coming out, as displayed below:
Please enter the recommended maximum staff cost:
900
You entered: 900.0
256.0
484.0
712.0
824.0
The total staff cost of Unit One is £824.0
The total staff cost of Unit Two is £0.0
252.0
504.0
The total staff cost of Unit Three is £504.0
208.0
416.0
650.0
884.0
1131.0
1378.0
The total staff cost of Unit Four is £1378.0
208.0
464.0
688.0
944.0
The total staff cost of Unit Five is £944.0
266.0
461.0
653.0
845.0
1037.0
The total staff cost of Unit Six is £1037.0
The total staff cost of Unit Seven is £0.0
480.0
The total staff cost of Unit Eight is £480.0
192.0
348.0
543.0
711.0
935.0
The total staff cost of Unit Nine is £935.0
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at TEST.main(TEST.java:48)
Any ideas what could be causing this?

The following lines are giving you an error:
Unitnum = inFile.nextLine();
Unitnum = inFile.nextLine();
You could wrap them in:
if (b < shopunits - 1) {
...
}

You have reached the end of the file and the Scanner tries to read the nextLine when at the end of the file which is causing this issue.

What Adarsh said is most likely correct, what you should do is wrap it in a while loop.
while(infile.hasNextLine()){
...
}
This way when it gets to the end it wont fail on you.
I went through and edited your code for formatting, it was hard to follow at first. I think the problem with your if block was there were no brackets on it.
Try this:
if(total > recommended_max){
System.out.println("Higher");
}else{
System.out.println("Lower");
}
I know it works without brackets sometimes but sometimes depending on how or where it is written it might not. so its always good to put them on.

The reason why the output of the if statement isn't coming is that the statement is outside the loop. Formatting your code properly should help you identify such errors earlier.
The curly brace ending the for (int b = 0; b <shopunits; b++) loop is located on the same line with total = 0; i.e. before the if statement. That is why the conditional is not reached during the loop.
Another problem is that your code consumes the new lines between the shops after processing the current shop. This works as long as there is a next shop; however, this breaks as soon as you reach the last shop.
To fix this problem, add checks before consuming new lines, like this:
if (!inFile.hasNextLine()) break;
Unitnum = inFile.nextLine();
if (!inFile.hasNextLine()) break;
Unitnum = inFile.nextLine();
Alternatively, you could protect the current block of nextLine() reads with a single if, like this:
if (b != shopunits-1) {
// Skip lines only if we haven't reached the last block
Unitnum = inFile.nextLine();
Unitnum = inFile.nextLine();
}
Once you move your if statement inside the loop and fix this problem, your program should run correctly.

For the error at the end, it seems that below at end of for loop tries to read lines after each iteration:
Unitnum = inFile.nextLine();
Unitnum = inFile.nextLine();
So either you should have 2 blank lines at the end of your file, or you should read a line at the beginning of the loop:
while(inFile.hasNextLine()) {
Unitnum = inFile.nextLine();
saleassist = inFile.nextInt();
.......
}
Second problem about the "if" block is related to the value of total being set to 0 at end of each iteration:
hour= 0;
rate = 0;
total = 0;
you need additional variable declared outside the outer loop, to hold the sum of totals across loops.
double sumOfTotal=0;
......
System.out.println("The total staff cost of " + Unitnum +" is £"+ total);
//this holds the sum of totals across loops
sumOfTotal += total;
......
total=0;
}
if (sumOfTotal > reccomended_max)
System.out.println("Higher");
else
System.out.println("Lower");

Related

How to add a variable to another variable that's already set

My homework is to create a program that takes a list of numbers and prints out the highest number divisible by four.
List would look like this:
12
16
87
58
25
73
86
36
79
40
12
89
32
Input should be:
40 because it is the highest number there divisible by four.
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int saved = 0;
int saved2 = 0;
for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
for (boolean bull = true; bull == true; bull ^= true) {
if (i > saved) {
saved -= saved2;
saved += i;
saved2 += i;
}
}
System.out.println(saved);
}
}
}
The input of my code is
12
16
I don't really understand why this is doing it, but it seems to me that I'm adding the variables wrong. The homework page on adding variables does not specify how to add variables to each other.
Does anyone have a tip to improve the code in anyway, or find a way to make a fix my code? Thank you.
welcome to Java.
First you are saying you got input, but that is output. Input is what you enter, and output is what you get printed.
Then there is a mistake in your for loops. You have too much going on in one place. By the logic which is implemented, your program will exit first level for loop whenever your entered value is not divisable by 4.
Read on for loops if you want to learn more https://www.learnjavaonline.org/en/Loops.
I recommend to start from while loops instead. The logic whould be this:
1. create variable to hold the correct answer saved
2. create another one to hold the value read from console i
3. start the while loop with condition i = scanner.nextInt()
3.1 check if the value just entered i is divisable by 4
3.2 if it is, then compare if it's larger than the one was saved before (initially saved value will be 0)
3.3 if it is larger, then assign the read value i to the saved
4. At the end of the loop, you will have the highest number divisable by four in your saved variable. Print it.
I will provide some help, according to
How do I ask and answer homework questions?
for (int i = scanner.nextInt(); i % 4 == 0;i = scanner.nextInt())
This only reads as long as ALL inputs are divisible by 4, that is why it ends at 16, because 87 is not divisible by 4.
for (boolean bull = true; bull == true ;bull ^= true)
This needs explanation by you, but I am pretty sure that it unconditionally executes the body of the inner loop exactly once. (Not 100% sure, because the representation of true and false could be weird in your machine. Should 0 be the representation of true, i.e. really weird, then it is an endless loop, which does not match the output you describe...)
System.out.println(saved);
This executes exactly once per input, except the last one, which is not a multiple of 4.
The value of saved is identical to input, as long as it is increasing.
These hints explain the unexpected output.
If you inspect the details of what the problem is, you should be able to improve your coding attempt.
This is how I super-quickly fixed in your code.
Note that there are no statements about the possible minimum value and about how do you stop the input. Therefore the solution is pretty-straightforward, it just reads the input until integers are present there.
This article may be useful about handling the input from the Scanner.
I hope the comments in the code will help. Add comments if there are any questions. Good luck!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int currentMax = Integer.MIN_VALUE; // you may set negative or 0 if you know that all the input is positive
// int saved2 = 0; // no need for this variable
while (scanner.hasNextInt()) { // you can make a better input handling, especially if you know when it should end the input. Now it will end on any non-integer input line
int i = scanner.nextInt();
// for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
// for (boolean bull = true; bull == true; bull ^= true) {
if (((i % 4) == 0) && (i > currentMax)) {
currentMax = i;
// saved -= saved2;
// saved += i;
// saved2 += i;
// }
}
}
System.out.println(currentMax); // moved out of "for" or "while" cycles. Print the value after the input has ended.
}
}

Java: Reading from a text file && Check whether the graph is complete or not

I have a school assignment that I finished most of, but I can't figure out how to read from a text file, and I'm having a certain problem regarding the code, The task I was given is:
"Write a program to read an input file named “input.txt”. The file
consists of several graphs. Each graph starts with a line containing
the number of vertices n, where 1 < n < 200. Each vertex is labeled by
a number from 0 to n-1. The second line contains the number of edges
l. After this, l lines follow each containing two vertex numbers
representing an edge. An input with n = 0 marks the end of the input
and is not to be processed.
You have to choose an appropriate data structure to represent the
graph. Indicate whether its Complete/has a self loop/ has an isolated
vertex "
Sample Input:
4
5
0 1
2 0
0 3
1 2
2 3
3
3
0 1
1 2
2 0
0
Sample output:
Not Complete/No Self-Loop/No Isolated Vertex
Complete/No Self-Loop/No Isolated Vertex
I used adjacency matrix, I wrote code that reads the edges, decided whether it has a self loop and whether there's an isolated vertex.
1- I wrote a code for finding whether it's complete or not, but it doesn't behave the way I want it, it always shows that It's not complete.
2- I am not familiar with the way to read inputs from a text file, so please I need help.
The part where I have to make it read any amount of matrices, is kinda easy (but leaving a hint for it is always welcomed hehe), but I just wanna make sure I know how to do the two steps above before I do it, I'd really appreciate leaving comments so I could learn whatever step you help me with, anyway, this is the program:
package phase1project;
import java.util.Scanner;
public class Phase1Project {
public static void main(String[] args) {
int max = 2000; //declare the max element for the array
int[][] adj= new int[max][max]; //declare the array
int n; //nodes
int l; // to determine the max number of edges
int loopChecker = 0;//To check whether there's a loop or not
int isolatedCounter = 0;
int completeCounter = 0;
int subCounter = 0;
int origin; //to determine where the edge starts
int destination; //to detemine where the edge stops
int i,j; //for the loop
Scanner input = new Scanner(System.in); //to scan inputs
System.out.println("Enter the number of vertices: ");
n=input.nextInt();
while(n<1 || n>200){ //nodes/vertices should be between 1 and 200
System.out.println("\nWrong input! Insert a numbe between 1 and 200\n");
n=input.nextInt();
}
System.out.println("Enter the number of edges: ");
l=input.nextInt();
System.out.println("Enter the begining of the edge then press enter then enter the end side of the edge to input it correctly.\n");
for(i=0;i<=(l-1);i++){ //a loop that populates the adjacency matrix
System.out.println("Enter edge "+i+": >> (0 0) to quit: ");
origin = input.nextInt();
destination = input.nextInt();
adj[origin][destination]=1;
}
System.out.println("\n\n\nThis is how your graph looks like:\n");
for(i=0;i<=(n-1);i++){
for(j=0;j<=(n-1);j++)
System.out.printf("%4d",adj[i][j]);
System.out.printf("\n");
}
//////////////////////////////////////////////////////////////
//Loop Checker starts from here
for(i=0;i<=(n-1);i++){
if(adj[i][i]==1){//If there's a 1 in the same place
loopChecker=1;
break;
}
}
if(loopChecker==1){
System.out.println("Self Loop");
}
else{
System.out.println("No Self Loop");
}
//Loop Checker ends here
///////////////////////////////////////////////////////////////
//checks whether the graph is complete
for(i=0;i<=(n-1);i++){
subCounter=0;//reset
for(j=0;j<=(n-1);j++){
if(adj[i][j]==1){
subCounter+=1;//buffer variable
}
if(subCounter==(n-1)){
completeCounter+=1;//this counter incriments if the whole line has 1s that equal n-1
}
}
}
if(completeCounter == n){
System.out.println("Complete");
}
else
System.out.println("Not Complete");
//end of complete or not check
/////////////////////////////////////////////////////////////////////
subCounter =0;//reset
//checks whether the graph has an isolated vertex or not
for(i=0;i<=(n-1);i++){
for(j=0;j<=(n-1);j++){
if(adj[i][j]==0){
subCounter+=1;//buffer variable
}
if(subCounter==n){
isolatedCounter=1;
break;
}
}
subCounter=0;//reset
}
if(isolatedCounter==1){
System.out.println("There's an isolated vertex");
}
else
System.out.println("There's no isolated vertex");
//end of isolated check
///////////////////////////////////////////////////////////////////
}
}
I hope I'm not breaking any rule by posting this, if I did please tell me.
Thanks in advance ;)

Java- Saving score in a game

I'm having problems tyring to keep score in my "guessing" game. I have to use a for loop or while loop. I have it so 10 random numbers are created in a text file called mystery.txt and a file reader reads these numbers from the text file.
Your score starts at 0. If the user guesses the correct number from the text file they get -10 points. If they get the number wrong they add the the absolute value difference of the number they guessed from a number in the file. The lower the score in the end the better.
When I only run my if else statement once, it works correctly. Once I loop it more than once it starts to act up.
I have to use an if else statement and a for or while loop. Thanks!
Edit- Turns out I have to use a for loop not a while loop, I'm completely lost now.
How it should work:
When you run the program a text file gets generated with 10 different numbers (I already have the code for that ready) The user gets asked to enter a number, the number the user enters gets compared to the first file on the text file. If it is the same never they get -10 points to their score. If they get it wrong they get the difference of the number the guessed and the number in the text file added to the score. This is suppose to repeat ten times.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class lab4Fall15 {
public static void numberGuessingGame() throws IOException {
Scanner myscnr = new Scanner (System.in);
PrintWriter mywriter = new PrintWriter("mysteryNumber.txt");
int randomNumber;
int i = 0;
i=1;
while (i<=10) {
Random randomGen = new Random();
randomNumber= randomGen.nextInt(11);
// then store (write) it in the file
mywriter.println(randomNumber);
i = i + 1;
}
//Decided to use a loop to generate the numbers-------
mywriter.close();
FileReader fr = new FileReader("./mysteryNumber.txt");
BufferedReader textReader = new BufferedReader(fr);
int numberInFile;
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
int score= 0;
int a = 1;
while (a<=10) {
a=a+1;
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber= myscnr.nextInt();
if (userNumber==numberInFile){
score = score-10;
}
else{
score = score + Math.abs(userNumber-numberInFile);
}
System.out.println ("current score is: "+score);
}
System.out.println ("your score is "+score);
textReader.close();
}
public static void main(String[] args) throws IOException {
// ...
numberGuessingGame();
}
}
if (userNumber==numberInFile){
score = score-10;
}
I don't understand what you going to mean. but I can guess this. your above code not show any error. normally , you check your , above part of code. you take variable 'numberInFile'. sometime , your file reader take this with 'whitespace or String or e.t.c' . first you check this out put .you put manual data to this variable and check out put. if it work fine , you correct that function.
OK, first, let's just go over for loops, since that's what your question was asking about. From the code you provided, it seems that you already understand while loops, and that's good, because in Java, for loops are (usually) just while loops in disguise. In general, if you have this while loop,
int a = 0;
while (a < 10) {
// do stuff with a
a = a + 1; // or ++a or a++
}
You can always rewrite it like this:
for (int a = 0; a < 10; a = a + 1) {
// do stuff with a
}
By convention (and this convention is useful when you study arrays and Collection types) you'll want to index your loops from 0 rather than 1. Since you're just learning, take my word for it for now. Loop from 0 to n-1, not from 1 to n.
With that out of the way, let's tackle why you're getting the wrong answer (which, incidentally, has nothing at all to do with loops). Rewritten as a for loop, the ask-and-score part of your program looks like this.
for (int a = 0; a < 10; ++a) {
System.out.print ("Please enter a number between 0 and 10: ");
int userNumber = myscnr.nextInt();
if (userNumber == numberInFile){
score = score - 10;
} else {
score = score + Math.abs(userNumber - numberInFile);
}
System.out.println ("current score is: "+score);
}
You will note that nowhere in this section do you update the value of numberInFile. That means that every run of this loop is still looking at whatever value that variable had at the beginning of the loop. That value came from this line:
// the number in your file is as follows:
numberInFile = Integer.valueOf(textReader.readLine());
That line is executed exactly once, before the loop runs. If you want to load the next number every time the user guesses a number, you'll need to move it inside the loop. I'll leave that as an exercise to the reader.
You are not actually capturing the number the user is entering. Try this:
int userNumber = Integer.parseInt(KeyIn.readLine());

Debugger stops working

My program needs to allow the user to input an employee's name and total annual sales. When the user is finished adding employees to the array, the program should determine which employee had the highest sales and which had the lowest sales. It should then print out the difference between the two numbers.
In my code below, I have a totalPay class that holds the annual sales input by the user (it includes other variables and methods from a previous assignment that are not used here). The salesPerson class holds the employee's name and totalPay object, which includes their annual sales. (I realize this is overcomplicated, but I'm modifying my previous assignment rather than starting from scratch.)
When I run this code, it allows me to enter the name and sales, but when I enter "yes or no" to add another employee, it crashes and tells me there is a NullPointerException on line 58, noted in the code.
I've ran the debugger (without any breakpoints) and it just stops at line 46, noted in the code. It doesn't give an error message, it just doesn't update that variable and my "step into" buttons for the debugger grey out and I can't click them anymore. (I'm using NetBeans, if that's relevant.)
Any ideas would be much appreciated!
EDIT: Here is the output and error message.
Name? captain America
Input annual sales: 80
Add another employee? yes or no
no
Exception in thread "main" java.lang.NullPointerException at commission.Commission.main(Commission.java:58)
package commission;
//Commicaion calulator
import java.util.Scanner;
public class Commission
{
public static void main(String args [])
{
salesPerson[] emps = new salesPerson[10]; //Employee Array
String cont = "yes";
String n="";
double s=0;
int i=0;
salesPerson high = new salesPerson();
salesPerson low = new salesPerson();
// scanner object for input
Scanner keyboard = new Scanner(System.in);
//Enter in employee name
while (cont == "yes"){
System.out.print("Name? ");
n = keyboard.nextLine();
emps[i] = new salesPerson();
emps[i].setName(n);
//Loop of yes or no entering more employees
//If yes add another name if no continue with total Commision
//Enter in the sales amount of commistion
System.out.print("Input annual sales: ");
s=keyboard.nextDouble();
emps[i].pay.annual = s;
System.out.println("Add another employee? yes or no ");
keyboard.nextLine();
cont = keyboard.next(); //Line 46: Debugger stops here.
if (cont =="yes")
i++;
if (i==9){
System.out.println("You have reached the maximum number of employees.");
cont = "no";
}
}
i=0;
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual) //Line 58: It claims the error is here.
high = emps[i];
if (emps[i].pay.annual < low.pay.annual)
low = emps[i];
}
double diff = high.pay.annual - low.pay.annual;
System.out.println("Employee "+low.getName()+" needs to earn "+diff+" more to match Employee "+high.getName());
// Output table for composation with increments of $5000
// int tempAnnual =(int) pay.annual;
// for (i=tempAnnual; i<= pay.annual; i+=5000)
// System.out.println(i+" "+ pay.getReward(i));
}
public static class totalPay
{
double salary=50000.0; //Yearly earned 50000 yr fixed income
double bonusRate1=.05; //bounus commission rate of 5% per sale
double commission; //Commission earned after a sale
double annual; //Sales inputted
double reward; // Yearly pay with bonus
double bonusRate2= bonusRate1 + 1.15 ; // Sales target starts at 80%
public double getReward(double annual)
{
double rate;
if (annual < 80000)
rate=0;
else if ((annual >= 80000) || (annual < 100000 ))
rate=bonusRate1;
else
rate=bonusRate2;
commission = annual * rate;
reward=salary + commission;
return reward;
}
}
public static class salesPerson
{
String name; //Employee Name
totalPay pay = new totalPay();
public void setName(String n) //Name
{
name=n;
}
public String getName()
{
return name;
}
}
}
You create this array of max size 10:
salesPerson[] emps = new salesPerson[10];
but only create and assign an object reference for each SalesPerson object entered. Since you only enter 1 name, only the 1st entry in the array is valid, then remaining 9 are null. You then attempt to iterate through the entire array (emps.length is 10 ):
for (i=0; i<emps.length; i++){
if (emps[i].pay.annual > high.pay.annual)
which leads to the NPE when indexing the first null reference. You need to change your loop to something like:
int numEntered = i; //last increment
for (i=0; i< numEnetered; i++){
if (emps[i].pay.annual > high.pay.annual)
It stops the debugger because it waits for your input using the keyboard. If you type the input and hit enter, the debugger will continue from there on.
By the way, your should read up on naming conventions and coding best practices for java
Your debugger is stopped because it's blocked on input coming in from the Scanner. This is specified in the documentation:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
That aside, you're fortunate to have entered that code block at all. You're comparing Strings incorrectly, so at a glance it'd look like you wouldn't enter that loop except under certain special circumstances. This is also the reason that your NPE occurs; you're initializing elements of your array under false pretenses (== with a String), so:
You may never initialize anything
You may only initialize the first thing (if (cont =="yes"))
I've only gone over a few of the high points, but for the most part, the blocking IO is why your debugger has stopped. The other errors may become easier to see once you start using .equals, but I'd encourage you to get an in-person code review with a classmate, tutor, or TA. There are a lot of misconceptions strewn about your code here which will make it harder to debug or fix later.

Java method passing/ordered logic inquiry

Let me first make it clear that this is for an assignment. I'm very new to programming so all guidance is greatly appreciated. The program I have to calculate is a parking fee charge for a $2.00 minimum for 3 hrs or less, .50 cents per additional hr, and charge is capped at $10/ per 24 hr period. Program must display most recent customer charge as well as running total. Constants must be initialized, Math.ceil must be used, and method calculateCharges must be used to solve each cust's charge. I get uber errors when I attempt to run this program, and you'll probably laugh when you see it, but where have I erred? I'm not looking for the answer to be handed to me, just looking for the logic behind how to get to the correctly written program. Please help!
package Parking;
import java.util.Scanner;
public class parking
{
private static final double THREE_HOURS = 2.00;
private static final double PER_HOUR_COST = .50;
private static final double WHOLE_DAY_COST = 10.00;
public static void main (String [] args)
{
double hoursParked = 0;
double cumulativeCharges = 0;
double storage1 = 0;
double storage2 = 0;
Scanner input = new Scanner(System.in);
System.out.print("\nThis program displays the charge for the most recent customer");
System.out.print(" as well as the running total of yesterday's receipts\n");
do
{ System.out.printf("Enter an number between 1-24 for hours parked in garage or -1 to quit:");
hoursParked = input.nextDouble ();
}
while((hoursParked > 0)&&(hoursParked <= 24)&&(hoursParked != -1));
if( hoursParked <= 3)
System.out.printf("Most recent customer's charge was: %.2f\n" , THREE_HOURS);
storage1 += THREE_HOURS;
if(hoursParked >= 18.01)
System.out.printf("Most recent customer's charge was:%.2f\n" , WHOLE_DAY_COST);
storage2 += WHOLE_DAY_COST;
double result = calculateCharges(hoursParked * PER_HOUR_COST);
System.out.printf("Most recent customer charge was:%.2f\n" , result);
cumulativeCharges = storage1 + storage2;
System.out.printf("Running total of yesterday's receipts is:%.2f\n" , cumulativeCharges);
} // end main
public static double calculateCharges (double hoursParked)
{
Math.ceil(hoursParked);
double total = hoursParked * PER_HOUR_COST;
return total;
} // end method calculateCharges
} // end class parking
In your while condition, the third condition is useless because if the value is positive, that necessarily means it is different than -1.
In your function you want to calculate the cost of parking time but you give as parameter a cost instead of a number of hours when you call your function. Is that normal? With that you will calculate the cost of the cost instead of the cost corresponding to a number of hours.
public static double calculateCharges (double hoursParked)
and
double result = calculateCharges(hoursParked * PER_HOUR_COST);
There's a couple things here.
Your while condition is checked at the end of the do loop, it is what allows you to break after reading hoursParked. Thus, the only way you are going to reach the code outside of the do loop (after the while), is if hoursParked is -1.
Secondly, when you do not have braces for your if conditions, you are only executing the first line after it, aka. the System.out.print's. Therefore, your first if condition will execute (printing the string), then storing 2.00 in storage1. Similarly, the second if condition will execute (printing the string), then storing 10.00 in storage2.
Because hoursParked is always -1, you are passing in (-1 * .5) to calculateCharges. You are not storing the result of Math.ceil() so it effectively does nothing. You are then returning (-.5 * .5) = -.25.
cumulativeCharges is just adding 2 + 10 in every case.
Suggestions - make sure you are encapsulating the code you want to execute inside the do loop, and only break after you have done your calculations on hoursParked.

Categories

Resources