Name/variable input and listing - java

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

Related

getting two data separated by space and calculate in java

My problem is I want to input two numbers separated by a space and getting those two numbers and compute those two numbers. for example, i typed "10 20", they are separated by a space and then I want to get and compute them as separate: 10 * 20 = 200..
what I have is a getter and setter for this part
these are my code:
MY GETTER AND SETTER CLASS
import java.util.*;
public class LabExer2
{
private String itemName;
private double itemPrice;
private int itemQuantity;
private double amountDue;
public void setItemName(String newItemName)
{
itemName = newItemName;
}
public String getItemName()
{
return itemName;
}
public void setTotalCost(int quantity, double price)
{
itemQuantity = quantity;
itemPrice = price;
amountDue = itemQuantity * itemPrice;
}
public double getTotalCost()
{
return amountDue;
}
public void readInput()
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the item you are purchasing.");
itemName = s.nextLine();
System.out.println("Enter the quantity and price separated by a space.");
//itemQuantity = s.nextInt();
//itemPrice = s.nextDouble();
}
public void writeInput()
{
System.out.println("You are purchasing " + itemQuantity + " " + itemName + "(s) at " + itemPrice + " each.");
System.out.println("Amount due is " + getTotalCost());
}
}
MY MAIN CLASS
public class MainLabExer2
{
public static void main(String[]args)
{
LabExer2 le = new LabExer2();
//still not finished because I can't figure out the process in the other class.
}
}
The output I wanted to have:
Enter the name of the item you are purchasing.
pencil
Enter the quantity and price separated by a space.
3 15.50
You are purchasing 3 pencil(s) at 15.50 each.
Amount due is 46.50
I want to get the 3 and 15.50 and compute. I don't know what to use or something, I'm just a beginner in java.
You can create two prompts, one to take in the itemQuantity int and another to take the itemPrice Double.
But if you want the user to input both values at once, you need to write a code in the readInput() method that will extract the itemQuantity value and the itemPrice value.
Try this:
public void readInput() {
Scanner s = new Scanner(System.in);
System.out.println("Enter the name of the item you are purchasing.");
itemName = s.nextLine();
System.out.println("Enter the quantity and price separated by a space.");
String userInput = s.nextLine(); //String to collect user input
//code to loop through String in search for Whitespace
for (int x=0; x<String.length(); x++) {
if (userInput.charAt(x) == ' ') {
//whitespace found, set itemQuantity to a substring
//from the first char in UserInput to the char before whitespace
itemQuantity = Integer.parseInt(userInput.substring(0, x-1));
//convert String to int
itemPrice = Integer.parseInt(userInput.substring(x+1, userInput.length()));
x = String.length();
} else {
itemQuantity = Integer.parseInt(userInput);
}
}
}
Pardon me if my code is not properly formatted, I'm new here.
Only need to convert the string into Integer, and string into Double. Then, to put 2 numbers and separate them, use the one-dimensional array and the split function.
try this:
public void readInput(){
//Enter the product of item name
System.out.print("Enter the name of the item you are purchasing: ");
ITEM_NAME = input.nextLine();
//Enter the quantity and the price for the item
System.out.print("Enter the quantity and price separated by a space: ");
String userInput = input.nextLine();
String[] inputArray = userInput.split(" ");
ITEM_QUANTITY = Integer.parseInt(inputArray[0]);
ITEM_PRICE = Double.parseDouble(inputArray[1]);
}

How to save the double variables on an array in 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.

Java: Returning Multiple Values to Main Method In Order To Compute Total

The code is below. The program runs a series of calculations based on data input by the user. My problem is that for the most important thing I'm looking for, total kg CO2 emissions, I continually get an answer of 0.0. What I need is a sum of the individual total emissions as calculated in each method, i.e. the values which are printed with the following: System.out.println(trans); System.out.println(elec); and System.out.println(food);
The total should be something like 25040 or whatever, depending on the value of the inputs provided by the user, but I'm constantly getting a total of 0.0., which is obviously false. Could have something to do with the way I've initialized my variables, or something to do with the limitations of returning values from methods. I just don't know what to do. How should I tackle this? All help greatly appreciated!
import java.util.Scanner;
public class CarbonCalc {
public static void main(String[] args) {
double trans = 0;
double elec = 0;
double food = 0;
giveIntro();
determineTransportationEmission(null);
determineElecticityEmission(null);
determineFoodEmission(null);
calculateTotalEmission(trans, elec, food);
//printReport(trans, elec, food);
}
//Gives a brief introduction to the user.
public static void giveIntro() {
System.out.println("This program will estimate your carbon footprint");
System.out.println("(in metric tons per year) by asking you");
System.out.println("to input relevant household data.");
System.out.println("");
}
//Determines the user's transportation-related carbon emissions.
public static double determineTransportationEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will first begin with your transportation-related carbon expenditures...");
System.out.print("How many kilometres do you drive per day? ");
double kmPerDay = console.nextDouble();
System.out.print("What is your car's fuel efficiency (in km/litre)? ");
double fuelEfficiency = console.nextDouble();
System.out.println("We now know that the numeber of litres you use per year is...");
double litresUsedPerYear = 365.00 * (kmPerDay / fuelEfficiency);
System.out.println(litresUsedPerYear);
System.out.println("...and the kg of transportation-related CO2 you emit must be...");
//Final calculation of transportation-related kgCO2 emissions.
double trans = 2.3 * litresUsedPerYear;
System.out.println(trans);
System.out.println("");
return trans;
}
//Determines the user's electricity-related carbon emissions.
public static double determineElecticityEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your electricity-related carbon expenditures...");
System.out.print("What is your monthly kilowatt usage (kWh/mo)? ");
double kWhPerMonth = console.nextDouble();
System.out.print("How many people live in your home? ");
double numPeopleInHome = console.nextDouble();
System.out.println("The kg of electricity-related CO2 you emit must be...");
//Final calculation of electricity-related kgCO2 emissions.
double elec = (kWhPerMonth * 12 * 0.257) / numPeopleInHome;
System.out.println(elec);
System.out.println("");
return elec;
}
//Determines the user's food-related carbon emissions.
public static double determineFoodEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your food-related carbon expenditures...");
System.out.print("In a given year, what percentage of your diet is meat? ");
double meat = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is dairy? ");
double dairy = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is fruits and veggies? ");
double fruitVeg = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is carbohydrates? ");
double carbs = console.nextDouble();
//Final calculation of food-related kgCO2 emissions.
System.out.println("The kg of food-related CO2 you emit must be...");
double food = (meat * 53.1 + dairy * 13.8 + fruitVeg * 7.6 + carbs * 3.1);
System.out.println(food);
System.out.println("");
return food;
}
//Calculates total emissions across all sources.
public static double calculateTotalEmission(double trans, double elec, double food) {
System.out.println("Your total kg of CO2 emitted across all sources is equal to...");
double total = trans + elec + food;
System.out.println((double) total);
System.out.println("");
return total;
}
}
Ah!! Thank you very much Lyju. I did the following and it all worked well.
From this:
double trans = 0;
double elec = 0;
double food = 0;
To this:
double trans = determineTransportationEmission(null);
double elec = determineElecticityEmission(null);
double food = determineFoodEmission(null);
The second problem which popped up here had to do with not correctly passing the Scanner parameter to the multiple methods.
I fixed that by adding the following to the main method:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double trans = determineTransportationEmission(console);
double elec = determineElecticityEmission(console);
double food = determineFoodEmission(console);
giveIntro();
calculateTotalEmission(trans, elec, food);
}
And because I had three scanner objects, one for each method, I simply removed the Scanners in each and can now pass a single Scanner from my main method to each of the others.

Output user data to display class

package developer;
import java.util.*;
import java.lang.Math.*;
public class Developer
{
static Scanner console = new Scanner(System.in);
String workType; // This will be either an app, or game
String name;
int pay;
int weekPay;
int hrsWorked;
double tax;
public Developer()
{
name = "Ciaran";
}
Developer(String appType, String coderName)
{
workType = appType;
name = coderName;
}// End developer
Developer(String appType, int pay) // Class to choose the pay rate depending on if it is a game or app
{
System.out.println("Are you coding an app or a game? ");
appType = console.next();
if(appType == "app")
{
pay = 20;
}
if(appType == "game")
{
pay = 30;
}
else
{
System.out.println("Please enter either 'app' or 'game' ");
}
}// End developer
Developer(int hrsWorked, double tax, int weekPay, int pay) // Class to choose the tax bracket which the developer is in
{
System.out.println("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
weekPay = hrsWorked * pay;
if(weekPay >= 865)
{
tax = 0.4;
}
else
{
tax = 0.21;
}
}// End developer
Developer(int weekPay, int tax) // Gets the pay after tax
{
weekPay = weekPay * tax;
}// End developer
public void display()
{
System.out.println("This display method works");
System.out.println("User: " + name);
}
public static void main(String[] args)
{
Developer myDev = new Developer();
myDev.display();
} // End main
}// End public class developer
I am trying to get this program to ask the user what their name is; if they are developing a game or app and the amount of hours worked on it. With all this information I want to calculate how much the dev earns including tax. I cannot seem to get the display() method to ask the user the questions though and I have no idea what to do. I am hoping somebody out there can help me.
System.in will read input from the command line. You should wrap it with a java.util.Scanner and nextLine like this:
Scanner scanner = new Scanner(System.in);
String user_input = scanner.nextLine();
Be sure to check
scanner.hasNextLine()
before continuing or you'll get an error.
There are few things that could be done differently in your code, so let's break it down:
1.No need to make console static type, you can use:
private Scanner console = new Scanner(System.in);
2.weekPay is of type int, but your tax is double, if you don't want weekPay to be cast to integer, change it to:
double weekPay;
3.Later on, you are calculating weekPay after tax, so let's introduce a variable for that:
double weekPayAfterTax;
4.All these Developer() methods are constructors, and I think you are slightly confused here. Of course, you can have many constructors, but for us, let's keep only the no-params constructor:
public Developer() {
name = "Ciaran";
//you could initialise all the other variables here as well,
//I'll leave it as an exercise for you :)
}
5.Let's create a method that will ask all the questions and set respective variables:
void setData() {
//let's get the name
System.out.print("What's your name: ");
name = console.nextLine();
System.out.print("Are you coding an app or a game? ");
//since we want the user to enter 'app' or 'game'
//we need to loop until we got these
//we can do this by creating endless while loop,
//which we will end when we have correct input
while (true) {
workType = console.next();
if (workType.equals("app")) {
pay = 20.0;
//stop the loop
break;
}
else if (workType.equals("game")) {
pay = 30.0;
//stop the loop
break;
}
else {
System.out.print("Please enter either 'app' or 'game': ");
//back to top
}
}
//ok, we're out the loop, let's get number of hours
System.out.print("Please enter how many hours you have worked this week: ");
hrsWorked = console.nextInt();
//calculate weekPay
weekPay = hrsWorked * pay;
if(weekPay >= 865) {
tax = 0.4;
}
else {
tax = 0.21;
}
//calculate pay after tax
weekPayAfterTax = weekPay - weekPay * tax;
}
6.Let's update our display() method to show all the info:
public void display() {
System.out.println("This display method works");
System.out.println("User: " + name);
System.out.println("Work type: " + workType);
System.out.println("Pay: " + pay);
System.out.println("Week pay: " + weekPay);
System.out.println("Week pay after tax: " + weekPayAfterTax);
}
7.In your main method, you can finally create an instance of Developer class and get the data:
public static void main(String[] args) {
Developer myDev = new Developer();
myDev.setData();
myDev.display();
}
The code above can be improved (such as checking if user entered number where it's expected), and your problem can of course be done differently, but here's the start.
Please check out some tutorials to learn the basics, such as this one, or this one. Most of all, experiment and don't let others put you down for not understanding something.

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));

Categories

Resources