My variables are
float amountLeft, amount;
char v1;
My goal is to let the user know If he uses more than a $1000 he will be in debt, the user can keep purchasing but he will be in debt. I can't get my head around negative numbers. How would I keep track of the negative numbers?
For example: "You just went over your limit. You owe us -5$ "
If you want to take a look at my code here it is.
amountLeft = 1000.0f;
while(amountLeft > 0) {
System.out.println(String.format("%3s %,1.2f %3s", "You have" , amountLeft, "money remaining to spend."));
System.out.println("Enter the cost of the item you want buy");
amount = new Scanner(System.in).nextFloat();
System.out.println("are you sure you wanna purchase this item?");
v1 = keyboard.next().charAt(0);
if (v1 == 'y')
{
amountLeft = amountLeft - amount;
System.out.printf("%.2f",amountLeft);
You can to create a situation that allows that user to spend if he is negative if (amountleft < 0)
Also, that loop should be while (amount >= 0) because the user won't owe anything if he is at 0 dollars.
Simply add a new statement inside your amount left:
if (amountLeft < 0) {
// alert user that hes over the amount
}
Add this at the end of your code, and then you can print his negative amount every type the loop is executed.
You can then print the amount as per normal.
Variables can start at positive, and end at negative, or go from positive, to negative, to positive with no dramas.
Let me paraphrase your question. You want to let the user buy stuff even though his/her money is not enough. And each time he/she does that, you print "you owe us $xxx". But now you are printing "you owe us $-xxx". You basically want the negative number to be printed out as a positive number, right?
The other answers tell you how to check for negative value but you are actually asking how to print negative values as positive ones.
There is a method for this in the java.lang.Math class! You can print -5 as a positive number this way:
System.out.println ("You owe us $" + Math.abs(amountLeft));
Related
I have written this short code and I want to let users to enter bank balance.
Then in new confirm dialog box they will choose if they want to enter transaction amount.
If "YES" then they enter either positive or negative numbers.
If entered value is negative so program with subtracts transaction amount from bank balance.
If entered value is positive so program will add transaction value to bank balance.
At the end if user selects "No" button in confirm dialog box so program will terminates with results of calculation!
Question:
when I enter numbers for bank balance and transactions so I get wrong answer!
I tried to user while loop and do while but I still get wrong results!
double total = 0;
String blc = JOptionPane.showInputDialog(null,"Enter the balance");
double balance = Double.parseDouble(blc);
int trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
while(trcsn == JOptionPane.YES_OPTION){
String transaction = JOptionPane.showInputDialog(null,"Enter amount:");
double trc = Double.parseDouble(transaction);
trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
if(trc < 0){
total = balance - trc;
}else{
total = balance + trc;
}
}
JOptionPane.showMessageDialog(null,total);
1: I enter 1000 dollars as bank balance.
2: I enter 1050 (positive) as transaction amount.
3: I enter -500 (negative value) as transaction amount for second try.
4: Answer is 1500.00 which is wrong!
1000 + 1050 = 2050.00
2050 - 500 = 1550.00
Answer should be 1550
Why answer is wrong???
In this section:
if(trc < 0){
total = balance - trc;
}else{
total = balance + trc;
}
You are updating your total, but not the balance. From the snippet you made, that remains unchanged.
As pointed out by #Fildor down in the comments below, at the moment you have a bug since you are either adding positive numbers together or else, subracting a negative number (x - (-y) == x + y)). To fix this, simply replace the entire if block with total = balance + trc.
You would need to update your balance to have the same value of total, or else, do without total altogether and use the balance field.
You should do something like the following:
String blc = JOptionPane.showInputDialog(null,"Enter the balance");
double balance = Double.parseDouble(blc);
int trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
while(trcsn == JOptionPane.YES_OPTION){
String transaction = JOptionPane.showInputDialog(null,"Enter amount:");
double trc = Double.parseDouble(transaction);
trcsn = JOptionPane.showConfirmDialog(null,"Transaction: ","",JOptionPane.YES_NO_OPTION);
balance += trc;
}
JOptionPane.showMessageDialog(null,balance);
First, you need to replace your if statement with a += statement. This is because subtracting when trc is negative and adding when trc is positive is equivalent to adding the absolute value of trc every time, which is probably not what you want to do. Second, you need to use 1 variable for balance, and track the changes over time. total is meaningless in the previous code, as it overrides its own value every time that your if statement executes.
double updatedBalance = (trc < 0) ? balance - trc : balance + trc;
total = updatedBalance;
Like the above answer suggests you need to update the balance.
Hi I'm new to Java and for my intro class I have to program something that does the following: Define a problem with user input, user output, While Statement and some mathematical computation.
What I want to do is have it prompt the user for feet and inches for height, if it's over 5'8 they can't go on the roller coaster; if it's 5'8 or less they can. I realize this would be much easier with like an if else kind of thing but I'm required to use while; also we haven't covered do while yet so I can't use that either. I'm probably messing up horribly and there's some better way to do this, but this is what I have so far.
import java.util.Scanner;
public class coasterHeight
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int feet;
int inches;
System.out.println ("Your must be at least 5'8 to ride this ride.");
System.out.println ("Please enter your height in feet:");
feet = keyboard.nextInt();
System.out.println ("Please enter your height in inches:");
inches = keyboard.nextInt ();
while (feet <= 5 && inches <= 8)
{
System.out.println("You can go on this ride.");
break;
}
{
if (feet >= 6 && inches >=9)
{
System.out.println ("You cannot go on this ride.");
}
}
}
}
So here's the problem. When the input meets the while requirements it works fine (it used to go on an infinite loop with "You can go on this ride" but I discovered break;), but for the if statement, nothing appears in the output. The "You cannot go on this ride", nothing appears, there's no error or anything it just ends the output after I enter a height that is over 5'8. Like I said this is probably awful but any help would be appreciated, thanks.
The reason your program doesn't work as you expect is because your logic is incorrect.
Look carefully at your conditions and think about the different possibilities the user can enter.
feet <= 5 && inches <= 8
The and operation && means both parts of this must be true at the same time in order for the statement to evaluate to true. So someone who is 5 feet 9 inches tall would cause this condition to evaluate to false.
The same problem occurs with feet >= 6 && inches >=9 in that someone who is 7 feet 1 inch tall would cause this condition to evaluate to false.
Also, it seems you have your conditions reversed. At the top of the program you say someone must be at least 5 feet 8 inches in order to go on the ride but then you check for less than that and allow them to go on.
Try using float or double instead, where float height = 0.00 or double height = 0.0.
Then you can use it in the while statement such as
while (height >= 5.8){
System.out.println("You cannot enter the ride");
break;
}
while (height < 5.8){
System.out.println("You can enter the ride");
break;
}
To answer this in pseudo-code (you can fill in the details using what you've already got):
while not valid input (not a number, is negative, etc.)
get height from user
if height allowed on ride
say "ok"
else
say "no dice"
As another note: notice that feet <= 5 && inches <= 8 is true for (for example) feet = 7 and inches = 1. I feel they should probably be allowed on the ride.
Please note that I while I am comfortable with Java, I am not exceptionally gifted nor do I know all the jargon, so please explain your answers with very little coder jargon and as much normal English, or explain what the jargon means after you use it. Also, this is my first time with Stackoverflow, so let me know if this was a decent question and give me some pointers.
I am taking an AP Computer Science class at my high school. We use Java. We were recently taught do-while loops and I just completed the "lab" that uses do-while loops, however, there is an issue.
Firstly, let me explain the lab. The program generates a random integer between 1-10 which the user must guess (guess is stored as an int using a scanner), there are a few integer values which track number of guesses, how many guesses were greater than the computer integer, and how many were too low. When you look at my code, you will notice that I have a System.out.println(compGen);//compGen is the computer generated int. The purpose was to test the code.
The issue is in the if-statement that compares userGen (user guess) and compGen.
if(userGen==compGen)
{
//do a lot of stuff
}
In this if-statement, it is not printing the correct SOPs that I have written IF the user guesses more than once. HOWEVER, I did not write this into the program, it seems to do it on its own. I used the SOP I mentioned early where the compGen int is printed, and I typed that in as my first guess and it worked perfectly. Everything in the if-statement block executed perfectly and printed everything correctly. However, when I did it as my second guess, third guess, or any guess that was not the first one, NOTHING was printed. See code below and run it. I don't believe this should make a difference, but the IDE that I use is Eclipse, hence the package statement. Please help.
package Chapter_3.Lab03_Chapter3;
import java.util.*;
public class Guess
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = userInput.nextInt();//USER GUESS
do
{
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
{
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
}
while (userGen != compGen);//condition to be ultimately checked
}
}
I haven't been able to figure out what is wrong. At one point I deleted the entire if-statement and re-typed it (I knew it wouldn't do anything, but I had to try). This issue makes no sense to me. There are no errors or anything that pop up, nothing pops up on the console which scares me a little. Thanks in advance.
First off, a lot of text you put here. Maybe try to minimize the problem next time as a suggestion ;) Otherwise everything is fine
To your problem. Let me minimize your code and then explain to you, what happens.
1. The Code
int val = scanner.nextInt();
do {
if (val < 5) {
// too low
val = scanner.nextInt();
} else if (val > 5) {
// too high
val = scanner.nextInt();
} else {
// correct
// THIS CODE DOESN'T RUN?!
}
} while (val != 5);
2. What does your code do?
You read your first number before your loop. That's fine. Then, you enter an if-elseif-else statement. Note, that once inside one of those blocks, the other blocks won't get executed. Now the problem is, that you read your next user inputs inside of the if-elseif! The program reads the next value and leaves the whole if-elseif-else. Your code does not execute, because the loop then ends before the next iteration, therefore the correct user input is not going through the if-elseif-else at all.
3. The solution
Remove all nextInt() reads and just have one as the first thing inside the loop:
int val;
do {
val = scanner.nextInt();
if (val < 5) {
// too low
} else if (val > 5) {
// too high
} else {
// correct
// THIS CODE RUNS NOW!
}
} while (val != 5);
Such things, structures that need to do something at least once before checking the loop condition, are usually done with do while loops rather than while loops
You are setting user input during the loop, and it is then checked afterwards. Try moving the body of the else if(userGen==compGen) block to after the loop like this:
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = userInput.nextInt();//USER GUESS
do
{
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
}
while (userGen != compGen);//condition to be ultimately checked
//The numbers have matched since it exited the loop.
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
The while condition is checked as soon as the program reaches the end of the code inside the loop. So suppose they enter the wrong number; the program says it's too low or too high, and then asks for another number:
userGen = userInput.nextInt();//new guess
Now suppose this new number is the correct one. The program finishes your if statement, then gets to the end of the loop. Then, at that point, userGen is equal to compGen. So the while condition fails, and the program exits the loop immediately, without ever getting to the code that prints the results.
One way to solve it would be to move the logic for userGen == compGen, that prints the results, outside the loop--that is, after the end of the loop. That way, it will be executed whenever the loop is exited. Note that when you exit the loop, we know that userGen == compGen, because if it weren't, the loop would go back.
Let's say the computer generated number was 3, and you guess 5.
5>3, so the if(userGen > compGen) statement executes:
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
you print the message, get a new guess, then increment your counter... but when you get the new guess, say it was the correct answer 3, userGen is now equal to CompGen (both are 3) and now the
while condition is evaluated:
while (userGen != compGen)
this is now false because userGen == compGen (both are 3). Your code never gets a chance
to print the correct message because the loop exits before it can happen. hope that helps
Your userGen is not being checked after every user input.
The problem is that you have your check inside an else-if block, which will check the end of the while statement before it loops back through again.
If you change
else if(userGen==compGen)
to
if(userGen==compGen)
then because it is not apart of the if-else block, it will be checked after every input (before the while condition is checked)
Alternatively you could move your user-input to the start of the do-while block like so:
package Chapter_3.Lab03_Chapter3;
import java.util.*;
public class Guess
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);//Scanner
int compGen = (int)(Math.random()* 10 + 1);//compGen is computer number
System.out.println(compGen); //USED TO VERIFY FAILURE. VALUE WAS ENTERED TO TEST CODE
int guessTrack = 0;//tracks number of guesses
int tooHighTrack = 0;//CREATING INTS TO TRACK STUFF
int tooLowTrack = 0;
System.out.println("Welcome to the integer guessing game that everyoone loves!");//PROMPT
System.out.println("Please enter your guess for the integer. Remeber, it is between one and ten.");//GREETING
int userGen = -1;//USER GUESS
do
{
userGen = userInput.nextInt();
guessTrack++;//Increase guess value
if(userGen > compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too high!");//inform user of bad guess
userGen = userInput.nextInt();//new guess
tooHighTrack++;//if guess is too high, this int tracker increases
}
else if(userGen < compGen)//checks user value in relation to computer generated int
{
System.out.println("Try again! Your guess was too low!");//inform user of guess
userGen = userInput.nextInt();//new guess
tooLowTrack++;//increases if user guess is too low
}
else if(userGen==compGen)//if both values are equivalent, execute THIS IS THE PROBLEM STATEMENT!!
{
System.out.println("Great job! You guessed the right number!");//congratulate
if(guessTrack>1)
{
System.out.println("It took you: "+guessTrack+" guess to get the right answer.");//print guess tracked int
}
else
{
System.out.println("It took you: "+guessTrack+" guesses to get the right answer.");//print guess tracked int
}
System.out.println(tooHighTrack +" guesses were too high and "+ tooLowTrack+ " were too low.");//print how many guess were too big or too low
System.out.println("HELLO"); //Used to verify failure of code
userInput.close();//close scanner object
}
}
while (userGen != compGen);//condition to be ultimately checked
}
}
This will cause your if-else block to be checked everytime a user inputs data before the conditions for the do-while are checked.
This question already has answers here:
min change greedy algorithm in java
(2 answers)
Closed 8 years ago.
I have a cashregister program that inputs purchases and payment and outputs the change due. i need it to not give just an amount but what particular coins/dollars user should get back. heres two methods i have
public void recordPurchase()
{
System.out.print("Enter total purchase price or negative number to end: ");
double input = keyboard.nextDouble();
while(input > 0)
{
purchase = purchase + input;
System.out.print("Enter total purchase price or negative number to end: ");
input = keyboard.nextDouble();
}
}
public double giveChange(Money moneyTypes)
{
double change = payment - purchase;
purchase = 0;
payment = 0;
//computes change rounding to two decimal places
change = (double)(Math.round(change*100))/100;
return change;
}
I need to output what coins/dollars person should get back. i have the money types saved in an array called moneyTypes. for example if the change due is $1.06 it would output you receive a dollar nickel and penny.
any advice would help. Thanks! if you need to see more of the code let me know
I'll give you an advice how to do it, not a solution.
Make a list of possible coin/note values.
Then from the biggest to lowest, compute how many times it fits into the remainder, and subtract this amount of money from the value. Make a note of the number of coins/notes.
This way, you will get the numbers you need.
count = Math.floor(remainder/coinValue) might help you.
I'm having some problems with my program, i ask the user to enter the start population,daily growth in percent, and how many days they will multiply. Then calculate the end population for each day, while making sure they are constraints to the user entered data. I keep getting back the same results for each day and the constraints aren't doing their job either.
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
for (int days=0;days<=daysofIncrease+1;days++)
{
if (startPopulation>=2 || increase >0 || daysofIncrease>=1)
{
endPopulation=(startPopulation*increase)+startPopulation;
JOptionPane.showMessageDialog(null,"This is the organisms end population: "+endPopulation+" for day: "+days);
}
else
{
input=JOptionPane.showInputDialog("Please enter the starting number of organisms");
startPopulation=Double.parseDouble(input);
input=JOptionPane.showInputDialog("Please enter their daily population increase as a percentage");
increase=Float.parseFloat(input);
input=JOptionPane.showInputDialog("Please enter how many days they will multiply in");
daysofIncrease=Double.parseDouble(input);
}
}
}
}
Your line
endPopulation=(startPopulation*increase)+startPopulation;
Will not calculate the end population correctly. You haven't used daysofIncrease at all.
I think you'll need to loop through the days. Note that I have not tested this, may need tweaking, but it should give you the idea:
double interimPopulation = startPopulation;
for (int days=1; days<=daysofIncrease; days++) {
interimPopulation *= (1.0 + (increase/100.0)); //get next day's population
}
endPopulation = interimPopulation;
I think you need to set somewhere in your loop this:
startPopulation = endPopulation;
And then you make another iteration of the loop.
Try this for example
endPopulation=(startPopulation*increase)+startPopulation;
startPopulation = endPopulation;
And if you don't want to lose the initial value of startPopulation,
just store it somewhere, before you change it (the way I suggest).