import java.util.Scanner;
public class NewClass {
public static void main(String[]args){
Scanner input=new Scanner(System.in);
String productMin="";
System.out.print("How much money do you have? ");
double money=input.nextDouble();
double minPrice=0;
double total=0;
double productPrice;
System.out.print("Please, insert the items in the invoice (the
name of product and its price):\n Insert \\\"stop\\\" as the name of
product to finish your input \n");
String productName=input.next();
productPrice=input.nextDouble();
total=total+productPrice;
while(!input.next().equals("stop"))
{
if(minPrice<productPrice)
{
minPrice=productPrice;
productMin=productName;
}
productName=input.next();
total=total+productPrice;
}
if(total<=money)
{
System.out.println("You have enough money !");
System.out.printf("%s is the item with the minimum price(which is SR
%.3f)\n",productMin,minPrice);
}
else
System.out.println("You don\'t have enough money");
System.out.println(total);
}//end of main method
}//end of calss
This is my code and it is not giving me the minimum price of the product and its name I tried a lot of things but still nothing and I'm running out of time can someone tell me where is the mistake????
This how the output should be
How much money do you have? 100
Please, insert the items in the invoice (the name of product and its price): Insert \"stop\" as the name of product to finish your input
Banana 20.200
Water 15.300
Honey 37.500
stop
You have enough money
Water is the item with the minimum price (which is KD 15.300)
And this my output
How much money do you have? 100
Please, insert the items in the invoice (the name of product and its price):
Insert \"stop\" as the name of product to finish your input
ss 20.100
dd 15.200
ff 37.500
stop
You have enough money !
ss is the item with the minimum price(which is SR 20.100)
in this line
while(!input.next().equals("stop"))
what happens if the user did not enter stop? - he/she still entered something...
You simply forgot to take the product price as an input in your while loop, you are taking it as a string.
Related
I need to write a program that calculates beverages for an entered amount of money. It was working before but I don't know if NetBeans just got tired of doing stuff or what because it suddenly couldn't get past the inputs. I can't figure out what I need to change to get it to function properly again and I can only assume it's the while loop that it's getting stuck on.
I have tried changing numbers, deleting spaces, altering the while conditions, moving line breaks around, and nothing works. Here is the official question:
Johnny is at the bar and he is going to drink beer.
Write a program that computes how many beers he can buy for money that he has. The program reads the amount and the price of beer, and prints how many beers he can afford. Consider also tax (10%) and tips (20%). Print the result in the following form: If a beer costs $3.25, Johnny can have 3 beers for $15 (he will pay $12.87).
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double br;
double amt;
double taxPrc;
double bill;
int count = 0;
System.out.printf("enter ur name: ");
String name = sc.nextLine();
System.out.printf("Enter price of beverage: $");
br = sc.nextDouble();
System.out.printf("Enter amt %s has: $", name);
amt = sc.nextDouble();
taxPrc = br * 1.1;
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
System.out.printf("if bevergae costs $"+br+", "+name+" can have "+count+" beverges for $"+amt+" (the bill will be $"+bill+").");
System.out.println();
}
My editor isn't showing that there are any problems. The file runs:
"enter ur name (name), Enter price of beverage $(#), Enter amt (name) has $(input number)"
then it just stops showing anything and leaves me on a blank until I stop it.
It's supposed to go on "if beverage costs $X, [name] can have [#] beverages for $[#] (the bill will be $[#])."
I was having an issues trying to get it to display the correct number for the bill less than the initial amount entered when it stopped working.
Just think about this block of code on its own for a bit
bill = taxPrc * 1.2;
while(bill<amt) {
count++;
bill = taxPrc * 1.2;
}
?
What in the while loop changes either bill or amt? Remember, a while loop runs until something in its conditional statement (in this case bill<amt) changes. As nothing in the while loop changes anything in the condition statement, it runs forever.
Your code doesn't change amt at all and just keeps resetting bill to the same value.
so im still new to java programming and for this program i need to make a program that calculates change for a vending machine. It is based of a 5 cent increment between a value of 25 cents to a dollar. for this assignment if i use a loop to force the user to input a value in bounds i get extra credit, since i originally was going to scratch because i wasnt getting it but soon did im back to using it. only thing is for one of my conditions it creates an infinite loop of the output message and im not sure why. any advice would be appreciated
/** Carmine A
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
float changeGiven;
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
int userInput;
int itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in 5-cent increments \n"
+ "Do not enter a decimal point");
//user inputs value to be set to variable
userInput= keyboard.nextInt();
//System.out.println("You entered ." +userInput + " as the price");
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
while(userInput>25 && userInput<100){
System.out.println("Price is in bounds");
System.out.println("Please enter a valid amount between 25-100");
itemCost=keyboard.nextInt();
}
}
itemCost=userInput;
//print out item cost based off users input
System.out.println("You enetered: " + itemCost +" as the items cost");
}
}
update
ok took what you guys said and made this
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
thanks for the help! knew it was something dumb, but this is why i ask for help so i can learn
so i believe it is frowned upon if i made another thread for the same program so i will add to this one.
i have completed just about everything i need but am having a few issues.
1. for some reason after i compile and run my code "Change Due:" prints twice, i am unsure why since i only have it once in a print statement but i can be missing it.
2.i need to print out in a money format and for some reason i have tried different formatting options and none will round (i have a feeling it is but it is not displaying because of the second "Change due:" printing) but can be wrong
3. on line 55 i am receiving this message and not sure why C:\Users\finst\Desktop\Intro to Java\Labs\Lab2\lab2Test.java:55: error: incompatible types: possible lossy conversion from double to int
changeRemainder= (changeDue*(double)100);
this is what i currently have:
/** Carmine
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
double userInput;
double itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in
5-cent increments");
//user inputs value to be set to variable
userInput= keyboard.nextDouble();
//while loop to make sure input stays in bounds
while(userInput<(.25) || userInput>(1.00)){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1
dollar");
userInput=keyboard.nextDouble();
}
//print out item cost based off users input
System.out.println("You entered: " + userInput +" as the items cost");
System.out.println("You entered a dollar to pay with");
//algorithm to calculate change due
int quarters;
int nickels;
int dimes;
int pennies;
int changeRemainder;
double changeDue;
double dollar=1;
//calculates change due
changeDue= (dollar - userInput);
//System.out.printf("%.2f" + "\n" ,changeDue);
//System.out.println("Change due:" + changeDue);
//makes the remainder into a number that can be used
changeRemainder= (changeDue*(double)100);
//calculates the amount of each coin needed to make the change
quarters= (changeRemainder / 25);
changeRemainder= changeRemainder % 25;
dimes= (changeRemainder/10);
changeRemainder= changeRemainder%10;
nickels=(changeRemainder/5);
changeRemainder= changeRemainder%5;
pennies=(changeRemainder);
//output statement to print coin amounts
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
As userInput is never updated in the loop then its value does not change and it will potentially loop for ever.
Maybe you mean userInput=keyboard.nextInt(); but you do not need two loops anyway.
userInput=keyboard.nextInt();
while (userInput<25 || userInput>100) {
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
You don't need 2 while loops; just one will do. In any case, your while loop checks the 'userInput' variable, but that never changes in the while loop; you are updating the itemCost variable instead.
I would use a Boolean for your while loop, and create an if else statement within this to check for valid entry and calculate the change. Hope this helps!
boolean end = true;
while (end) {
//retrieve user input of cost and assign value to variable
//create an if statement check if the value is valid
if(itemCost >=25 && itemCost <=100){
//retrieve user input for change entered
//calculate change for the user and display it
//end loop
end = false;
} else {
//invalid entry
end = false;
}
}
I am creating a bankteller loop java code. I am trying to ask the user for what amount of money they would like to deposit into their account. I can get this to work once. For example, they will enter in $20 the first time. Then they will decide to put in $10 more. However, instead of displaying the current balance at $30, it only displays the one recently entered (the $10). How do I fix this?
Here is my code for that part of the loop in the menu that calls the class:
else if( userInput == 3 ){
Account account = new Account();
System.out.print("\nHow much would you like to deposit?: ");
float money = input.nextFloat();
account.deposit(money);
}
Here is the code for deposit that is called:
public void deposit(float money) {
if (money < 0) {
System.err.println("Error: Can't deposit negative money.\n");
return;
}
else {
currentBalance = money + currentBalance;
System.out.println("Current balance: $" + currentBalance + "\n");
}
}
You want to maintain the total balance so far. However, the moment you create a new Account object, balance gets initialized to zero and thus losing previous balance.
What you need to do is create an Account object only once and then call deposit on the same Account object.
I am working on a program that mimics a vending machine, it needs to pull data from a .txt file and use that information in the program. I want it to ask the user to input their amount of money and give them change as well. I want to store the prices in 2d arrays as well as the item names then have the user pick an item to buy. I am not sure how to go about this!! I really need some help, this is what I have so far.
Code:
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
public class Vending
{
public static void main(String[] args) throws FileNotFoundException
{
System.out.print("Enter your food selection file: "); // User inputs file
Scanner input = new Scanner(System.in); // Keyboard input from user
Scanner fs = new Scanner(new File(input.nextLine())); // Scans in the file that was inputed
}
double price = 0;
while(fs.hasNextLine()){
fs.next();
price = fs.nextDouble();
System.out.print(price);
}
}
Item list file (Food.txt):
1 Honey roasted peanuts
1.50 Cheetos
1.50 Bugles
2 Synder’s Pretzels
1 Snickers
1 Twix
1.25 M n Ms
.75 Life savers
1 Twizzlers
1 Nutter Butters
1 Butter Fingers
1.50 King Size Kit Kats
1.25 Carrot sticks
.50 Juicy Fruit
.50 Spearmint Gum
.50 Five gum
3.50 Pepperoni
1.75 Cheez-Its
.25 Slim Jim
1.50 Lays Barbeque Chips
Here are some thoughts:
Instead of a 2-D array, create a simple Item
POJO that
holds the item's name and price.
Read in each line of the input file
and create one Item for each.
Store each of those in an array.
Rather than having the user input the precise name of the item they
want, emulate a real vending machine and assign each item a number.
E.g., iterate over the array and let each index represent the "item
number" and then print out the item price and name.
Now you can have your application's main function:
Read the file and create the array
Print out the options
Ask user to select an option
Ask user to provide money
"Return" the product (i.e. print "here's your item")
Calculate and "return" the change (i.e. print "here's your $x.xx back")
Here's a pseudocode for the change calculation using an Item object:
double calculateChange(Item item, double money) {
double price = item.getPrice();
// if assignment needs to handle "money < price", do so here
return money - price;
}
I am going to create a program that keeps track of the balance on a bank account. The program shall use a loop that continues until the user choses to exit by answering no to the question Do you want to continue?.
In the loop the user shall be asked to enter an amount (positive for deposit and negative for withdraw). The amount shall be added/subtracted from an account balance variable. All deposits/withdraws shall be saved as a history so that we can print it later. When the user choses to exit the loop the current account balance together with the account history (from the array/ArrayList) shall be printed.
Now, I want to use an array with ten slots for the history feature.
My question is how can I keep track of the all deposit, withdraw and current account balance (using an array with ten slots for the history feature) so that I can print it out while the user exits the program?
My code:
BankApp class:
package bankapp;
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
askingUser au = new askingUser();
System.out.println("WELCOME TO OUR BANK!\nYou have 100 SEK by default in your account.");
while (true) {
au.userInput();
System.out.println("Do you want to continue? Answer by Yes or No.");
String yesOrNo = input.next();
if (yesOrNo.equalsIgnoreCase("yes")) {
au.userInput();
} else if (yesOrNo.equalsIgnoreCase("no")) {
System.out.println("History: ");
//print out the transaction history
System.exit(0);
} else {
System.out.println("Invalid character input.");
}
}
}
}
askingUser class:
package bankapp;
import java.util.Scanner;
public class askingUser {
Scanner input = new Scanner(System.in);
double initialBal = 100;
public void userInput() {
System.out.println("Enter your amount: (+ve for deposit & -ve for withdraw)");
double inputAmount = input.nextDouble();
if (inputAmount >= 0) {
double newPosAm = initialBal + inputAmount;
System.out.println("Your current balance is: " + newPosAm + " SEK");
} else {
double newNegAm = initialBal + inputAmount;
System.out.println("Your current balace is: " + newNegAm + " SEK");
}
}
}
If you use an array, you have to keep track of the number of elements stored inside and resize the array when necessary. The easiest way would be to keep the history as strings in ArrayList. You would add one message to that list per transaction:
ArrayList<String> history = new ArrayList<String>();
void addToHistory(String transaction) {
history.add(transaction);
}
void printHistory() {
for(String s : history) {
System.out.println(s);
}
}
addToHistory("Withdrawal: 100 SEK" );
addToHistory("Deposit: 200 SEK" );
printHistory();
You need a queue to do that. However, for a simple, fast and primitive implementation you can:
Define an object called Transaction(deposit - double, withdraw - double, current account balance - double)
Add a List of Transactions into askingUser class as an attribute. I strongly recommend renaming the class name to AskingUser to make it seen as object.
At each operation add a new Transaction to end of the List you just added.
At exit, print out the last -say- 10 elements of the List; you can reach it through askingUser object. You can also define a function in askingUser class to print out the last 10 elements, if you make the function work according to selected number of elements, you can add number of Transactions to the function's inputs.