How to save the double variables on an array in java? - java

Good day! I am trying to make a program that will ask the user to input the total number of the items. After the input of the total items, the program should ask the price of each item, based on the input. After the input of the prices, the program should compute the total price and ask for the cash. If the cash is not sufficient to pay the items, allow the user to re-enter cash until he/she inputted enough to pay the bill. Lastly, it will print the change of the user.
My problem is, how to I compute the price of each item. I think I need an array to save each prices and compute them afterwards. Here is my program, I know its a mess, sorry im still a beginner. Hoping for a solution. Thank you so much!!
public class Store {
public static void main(String[] args) {
Scanner v = new Scanner (System.in);
int totalitems;
int change;
int cash;
double price[];
double totalprice;
System.out.print("Enter Total Number of Items: ");
totalitems = v.nextInt();
for(int loop=1; loop<=totalitems; loop++) {
System.out.print("Enter the price of each item: ");
price[totalitems] = v.nextInt();
}
//i need a solution here for array
System.out.print("Enter the your cash: ");
cash = v.nextInt();
if(cash < totalprice) {
System.out.print("Please input a sufficient amount: ");
cash = v.nextInt();
}else {
change = cash - totalprice;
}
System.out.print("Thank you! Your change is: " + change);
}
}

You can iterate over the price array, either in the old-fashioned way:
for(int loop=0; loop < totalitems; loop++) {
totalPrice = totalPrice + price[loop];
}
or, in the new way:
for (double itemPrice : price) {
totalPrice = totalPrice + itemPrice;
}
But you're forgetting something else as well: the price[] array isn't initialized. As soon as the totalItems is known, you must do
price[] = new double[totalItems];
Otherwise Java wouldn't know how much memory to reserve for the array.

Related

How do I convert my while loop to a for loop?

I am a beginner coder using Netbeans Java. I have created a code that initially asks how many gallons are in your gas tank. Then, it will have a while loop asking how many miles you will be traveling for this first run and how fast are you traveling. This will repeat with a while loop until you input '0' to stop adding trips. I am stumped on how to convert this while loop into only using For loops. I would greatly appreciate the assistance. Here is my code that has while loops.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tank;
double miles;
double speed;
double totalMiles = 0.0;
int choice;
double time;
double totalTime = 0.0;
double fuelConsumption;
System.out.print("How many gallons of gas is in your tank (Integer 1-15)? ");
tank = input.nextInt();
System.out.printf("%s%d%s\n\n" , "You have ", tank , " gallons of gas in your tank.");
System.out.print("Are you going on a trip (1 = Yes or 0 = No)? ");
choice = input.nextInt();
while (choice == 1)
{
System.out.print("How many miles are you traveling? "); // miles
miles = input.nextFloat();
System.out.print("What is your speed for this run (MPH)? "); // speed
speed = input.nextInt();
System.out.print("\n");
totalMiles = totalMiles + miles;
time = (miles/speed);
totalTime += (time*60);
fuelConsumption = (20*(tank/totalMiles));
System.out.print("Is there another leg in your trip (1 = Yes or 0 = No)? "); // asking another leg
choice = input.nextInt();
if (choice == 0)
{
System.out.printf("%s%5.2f%s\n","Your data for this trip is: \n"
+ "You traveled a total of about ", totalMiles , " miles.");
System.out.printf("%s%.2f%s\n" , "You traveled about " , totalTime , " minutes.");
if (fuelConsumption >= 2)
{
System.out.println("Your car has enough gas to return.");
break;
}
else
{
System.out.println("Your car will need more gas to return.");
break;
}
}
}
}
}
That is not a use case for a for loop, where we iterate over a known number of elements for do a known number of iterations. Like, repeat 10 times or such.
Technically it can be solved with a for loop, but that is abusing the concept a bit. The while loop is a perfect fit for that task.
This is not a place to use a for-loop, you use a for loop for something like this:
printAmount = 10;
for (int i = 0; i < printAmount; i++) {
System.out.println("Hello World");
}
Here you are using the for loop to print "Hi" for the amount in printAmount.
Your case is different: You want the while-loop to repeat while the input is "1" so you use a WHILE-loop.

Compound interest

import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually, monthly, daily;
double balance;
int year = 10 ;
System.out.println("Enter the amount you will like to deposit or type exit to end.");
int deposit = key.nextInt();
annually = deposit * Math.pow((1 + rate/1),year);
monthly = deposit * Math.pow((1 + rate/12),year);
daily = deposit * Math.pow((1 + rate/365),year);
while (deposit)
{
}
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
This is what I currently have. What I am trying to accomplish is to make a loop to add the first outcome with the next one. Also make one formula instead of having three to find the annually, monthly and daily.
First and foremost, asking someone to write out your homework is really unethical, and not helpful for you in the long run. If you don't care about the long run, consider taking a different class. In a career scenario, you're expected to write code on your own.
Secondly, to actually answer your question, here are some tips:
It seems like you want to gather a value (deposit) from the user, and then calculate the Compound Interest for said value. Your program also needs to not exit until the user says to exit. i.e. they want to calculate the CI for a set of numbers.
First step is to check the value from the user. If it is a number, then do calculations on it. If it is a String, then check if it is "exit". In Java, this amounts to writing out an if-statement, and making use of the very helpful "instanceof" keyword. If you haven't learned about that, give this a read, or ask your teacher.
For the calculations part, you simply do calculations on the user's input while the input is not a string set to "exit".
Finally, print out your calculations.
That's it. Your code already has the calculation formulas down, so you just need to code the logic for handling user input.
import java.util.Scanner;
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How much money you want to deposit?");
int principle = sc.nextInt();
System.out.println("what is the rate you want?");
float rate = sc.nextFloat();
System.out.println("After how many years, you want to see your money?");
int year = sc.nextInt();
System.out.println("How many compounds in a year?");
int partialTime = sc.nextInt();
double b = year * partialTime;
double a = 1 + (rate/(partialTime*100));
double x = principle * (Math.pow(a,b));
System.out.println("Your interest in given time would be " + x);
}
}
A couple of suggestions - since you want to check user input against both String and int types, you could define a String type variable to hold the user input, and then do a try/catch to parse it as an Integer, if it's not an Integer check if the input equals "exit" (using the String.equals() method).
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually = 0, monthly = 0, daily = 0;
double balance;
int year = 10, deposit = 0 ;
String userinput = "";
do {
try {
System.out.println("Enter the amount you will like to deposit or type exit to end.");
userinput = key.nextLine();
deposit = Integer.parseInt(userinput);
}
catch (Exception e){
if (!userinput.equals("exit")){
System.out.println("Didn't recognize that input, please try again...");
}
else{
break;
}
}
} while (!userinput.equals("exit"));
annually += deposit * Math.pow((1 + rate/1),year);
monthly += deposit * Math.pow((1 + rate/12),year);
daily += deposit * Math.pow((1 + rate/365),year);
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
Depending on how you want the output, you can easily adjust the scope of the loop to display the amounts after each valid deposit input, or just once at the end, after the user enters "exit".
Hope this helps.

Name/variable input and listing

I'm trying to create a program that allows the user to say, input (orange/apple/banana/etc), then the quantity they want to purchase, and the program will calculate the total. However, after trying Strings (Can't multiply them) and a few other options, I'm stuck. I've intensively browsed this forum along with countless guides, to no avail.
The IF statement I inserted was simply a last ditch random attempt to make it work, of course, it crashed and burned. This is all basic stuff I'm sure, but I'm quite new to this.
I would also like to display a list to choose from, perhaps something like
Oranges: Qnty: (Box here)
Apples: Qnty: (Box here)
Bananas: Qnty: (Box here)
Etc
But I'd really settle for help as how to allow the user to input a word, orange, and it is assigned the value I have preset so I can multiply it by the quantity.
All help is appreciated, criticism too of course, to you know, a reasonable extent...
Here's my code.
/* Name 1, x0000
* Name 2, x0001
* Name 3, x0003
*/
import java.util.Scanner;
public class SD_CA_W3_TEST1
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
double nameOfItem1, nameOfItem2, nameofItem3;
double quantityItem1, quantityItem2, quantityItem3;
final double apple = 0.30;
final double orange = 0.45;
final double strawberry = 2.30;
final double potato = 3.25;
final double turnip = 0.70;
final double carrot = 1.25;
double totalCost;
String strNameOfItem1;
System.out.println(" \t \t What would you like to buy today?");
System.out.print("Please choose from our fine selection of: oranges, strawberries, potatoes, turnips, and carrots. \n" );
System.out.print("Enter name of product ");
nameOfItem1 = in.nextDouble();
nameOfItem1 = If = nameOfItem1 (apple, orange, strawberry, potato, turnip, carrot);
System.out.print("Please enter a quantity to purchase");
quantityItem1 = in.nextDouble();
totalCost = quantityItem1 * strNameOfItem1;
System.out.print("The total cost of your purchase is: " +totalCost );
}
}
I would use a HashMap. Here's a good tutorial:
http://www.tutorialspoint.com/java/util/hashmap_get.htm
HashMap food = new HashMap();
food.put("Apple", 0.30);
food.put("Orange", 0.45);
...
then use
food.get("Apple");
to give you the price.
the grand total would be something like:
double quantity = 4.0;
double total = food.get("apple") * quantity;
Try using enums,
class Test{
public enum Fruits{
apple(0.30), orange(0.45), strawberry(2.30), potato(3.25);
private final double value;
Fruits(double value1){
value = value1;
}
public double getValue(){
return value;
}
}
public static void main(String[] args) {
int quantity = 0;
// Read your value here and assign it to quantity
System.out.println(Fruits.apple.getValue()*quantity);
}
}
Enum seems to be a good choice here. It would help you map your item names to the price easily instead of creating several double variables.
private enum Items {
APPLE(0.30), ORANGE(0.45), STRAWBERRY(2.30),
POTATO(3.25), TURNIP(0.70), CARROT(1.25);
double price;
Items(double price) {
this.price = price;
}
double getPrice() {
return price;
}
}
Use Scanner#next() to read in String and use Enum.valueOf() to validate and convert user input into one of your Items.
Scanner in = new Scanner(System.in);
System.out.println("What would you like to buy today?");
System.out.println("Please choose from our fine selection of: " +
"Orange, Strawberry, Potato, Turnip, and Carrot.");
System.out.print("Enter name of product: ");
String nameOfItem = in.next();
Items item;
try {
// Validate Item
item = Items.valueOf(nameOfItem.toUpperCase());
} catch (Exception e) {
System.err.println("No such item exists in catalog. Exiting..");
return;
}
System.out.print("Please enter a quantity to purchase: ");
int quantity;
try {
quantity = in.nextInt();
if (!(quantity > 0)) { // Validate quantity
throw new Exception();
}
} catch (Exception e) {
System.err.println("Invalid quantity specified. Exiting..");
return;
}
double totalCost = quantity * item.getPrice();
System.out.printf("The total cost of your purchase is: %.2f", totalCost);
Output :
What would you like to buy today?
Please choose from our fine selection of: Orange, Strawberry, Potato, Turnip, and Carrot.
Enter name of product: Strawberry
Please enter a quantity to purchase:3
The total cost of your purchase is: 6.90

How do I make my program continue only if the user enters certain values?

My code is supposed to simulate something similar to a vending machine. But there is a problem when I enter a price that is not one of my options, e.g. 0.82 the program still runs. How do I get it to only accept one of my options?
import java.util.Scanner;
public class VendingMachine
{
public static void main (String[] args)
{
double price;
Scanner keyboard = new Scanner(System.in);
System.out.println("Choose your price. Your options are: ");
double i;
for (i=0.25; i<=1.25; i+=0.25)
System.out.printf("$%.2f\n", i );
System.out.println("Enter your selection now: ");
price=keyboard.nextDouble();
System.out.printf("You chose the $%.2f option. ",price);
double deposit;
if (price<=1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit=1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit=2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit-price;
System.out.printf("Your change is $%.2f\n",change);
}
}
I tried something like this but it doesn't work. What is the best way to do this.
if (price==i)
System.out.println("You entered " + price);
else {
System.out.println("Invalide choice. Please try again.")
System.exit(0);
}
Here is an image if you find it easier to read.
You can use some sort of loop (while, do-while, for), which will continue to excecute the code until a condition is (or isn't) met.
Here is an example:
do {
code line 1;
code line 2;
code line 3;
...
} while(yourCondition);
If yourCondition is satisfied (yourCondition == true), the code will go back to code line 1 (will perform the code block between do and while) and it'll stop once the condition isn't satisfied(yourCondition == false). yourCondition could be any expression that returns a true/false result (boolean), such as 2+2==4.
If you want to keep looping for as long as yourCondition isn't met, you can add a ! before your expression, which will evaluate the opposite of your boolean like this (!yourCondition).
Now, if you understood how that works, you can easily apply it to your code.
If you want the user to enter only your displayed prices, I suggest the following, you shall edit to your exact desires.
//given you an open scanner
boolean isCorrectPrice = false;
System.out.println("enter price");
price = in.nextDouble();
while(!isCorrectPrice)
{
if(price%0.25==0 && price<=1.25 && price>0)
{
System.out.println("you entered "+price);
IsCorrectPrice = true;
continue;
}
System.out.println("incorrect price, re-enter ");
price = in.nextDouble();
}
//your code after user enters correct price
That will do the check. If your prices change, all you have to do is change the maximum price provided its still dividable with 0.25 or the condition price check.
Use BigDecimal (instead of double) to work with money. Its exact -- double isn't.
http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html
I would write a function to get the user input. It would not return until the
user had entered an allowed value.
Although my real answer is the one on the comments, you can use something like this. To check recursively if the correct value was given.
import java.util.Scanner;
public class VendingMachine {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Choose your price. Your options are: ");
for (double i = 0.25; i <= 1.25; i += 0.25) {
System.out.printf("$%.2f\n", i);
}
double price = checkMultipleValues(0.25,1.25, 0.25);
System.out.printf("You chose the $%.2f option. ", price);
double deposit;
if (price <= 1.00) {
System.out.println("Please insert 1 dollar. *This machine only accepts Loonies*");
deposit = 1;
} else {
System.out.println("Please insert 2 dollars.*This machine only accepts Loonies*");
deposit = 2;
}
System.out.println("Please press 'Enter' to simulate inserting money. ");
new Scanner(System.in).nextLine();
double change;
change = deposit - price;
System.out.printf("Your change is $%.2f\n", change);
}
private static double checkMultipleValues(double initial,double last,double step) {
System.out.println("Enter your selection now: ");
double price = keyboard.nextDouble();
for (double i = initial; i <= last; i += step) {
if (price == i) {
return price;
}
}
return checkMultipleValues( initial, last, step);
}
}
ADDENDUM
Since you like #Sello answer why don't you combine it with #MrD and have something like
do {
System.out.println("enter price");
price = in.nextDouble();
// System.out.println("you entered " + price);
} while (!(price % 0.25 == 0 && price <= 1.25 && price > 0));

Adding a list of user-inputted doubles to an Array

So my program, when instantiated asks the user how many "items" they want. My program then creates two arrays, one for the "item name" and one for the "item price". I use a loop to let the user input each item name and item price in their respective arrays, however I'm lost with the item price array. To use my loop, I need to utilize the "itemprice.length" element but I can't do that when I'm not working with Strings.
After the user inputs the "prices" of each item, I need to apply a multiplier to each array item and output it. So I want to, for example, have 3 items in the array: 1.20, 1.30, 1.40, and then I want the program to ask me for the "sales tax" of which I can enter 0.08 and it will then multiply 0.08 to each item and output a total.
Is there a way that I can make my program work so it allows the user to enter, let's say, 5 items and their prices and am I going about it the right way? Any way of doing this easier? Thanks!
public class Input
{
private Scanner keybd;
private String item;
private double cost;
private String[] costArray;
private String[] itemArray;
/**
* Constructor for objects of class Scanner
*/
public Input(int anyAmountofItems)
{
keybd = new Scanner(System.in);
costArray = new String[anyAmountofItems];
itemArray = new String[anyAmountofItems];
}
/**
* Mutator method to set the item names and costs
*/
public void setArray(){
for(int index=0; index < itemArray.length; index++){
System.out.println("Enter the item name: ");
itemArray[index] = keybd.next();}
for(int indexa=0; indexa < itemArray.length; indexa++){
System.out.println(itemArray[indexa]);
}
for(int indexb=0; indexb < costArray.length; indexb++){
System.out.println("Enter the item cost: ");
costArray[indexb] = keybd.next();}
for(int indexc=0; indexc < costArray.length; indexc++){
System.out.println(costArray[indexc]);
}
}
/**
* Accessor method to return the items cost with tax
*/
public double getTax(){
return costArray.length;
}
Use a Float[] and use Float.parseFloat(String str) to convert from a string to a float.
As an aside, when dealing with money, floating point is a bad idea, since there are always issues with precision. It is best to use ints/longs with the appropriate lowest currency unit (i.e cents in the US etc.)
you can try as:
System.out.println("Enter the sales tax: ");
double salesTax = keybd.next();
double totalTax =0.0;
double total = 0.0;
for(int indexc=0; indexc < costArray.length; indexc++){
System.out.println("Enter the item cost: ");
double cost = Double.valueOf(keybd.next()).doubleValue();
totalTax = totalTax + (cost * salesTax);
total = total + cost;
}
System.out.println("Total: " + (total-totalTax));
EDIT: TO calculate the total during inserting the cost.
It's not clear to me what your question is. Are you having problems with the item cost data? You are just reading in a String. You should read in an array of doubles instead.
costArray = new double[anyAmountOfItems];
// Then when reading use the appropriate Scanner method
costArray[indexb] = keybd.nextDouble();
A couple style notes:
You might want to consider using Lists instead of arrays. That way you don't have to worry about fixing the size of the arrays.
There is no need to use new variable names in each of the for loops. It just adds confusion. Instead of indexa, indexb, etc just use i.
Better yet, use the enhanced for loop for cases where you don't really need the index:
for( String item : itemArray ) {
System.out.println(item);
}

Categories

Resources