Calorie Counter Java - java

I'm self-teaching myself Java and came across this question.
It required the making of multiple methods and also taking user data and making it into an array.
I am confused because wouldn't an array only have to be either a float, or a int or a double or a String, it cant be both a String and a double. But the user is entering multiple flavors of data. I am adding the question below and also the code I have scripted so far.
enter image description here
I have attached an image of the question
import java.util.Scanner;
public class salesRecord {
String Itemname;
int Quantity;
float unitPrice;
static float total;
String status; //for credit or debit
void data() {
Scanner input=new Scanner(System.in);
System.out.println("Enter your Item name: ");
Itemname=input.next();
System.out.println("Enter your Quantity: ");
Quantity=input.nextInt();
System.out.println("Enter your Unit Price: ");
unitPrice=input.nextFloat();
System.out.println("What is your Status: ");
status=input.next();
total=Quantity*unitPrice;
}
void ShowData() {
System.out.println("Item name is: "+Itemname);
System.out.println("Quantity is: "+Quantity);
System.out.println("Price per unit is: "+unitPrice);
System.out.println("Credit or Debit: "+status);
System.out.println("Total Price is: "+ total);
}
public static void main(String[] args) {
salesRecord cus1=new salesRecord();
Scanner inputcashier=new Scanner(System.in);
System.out.println("How many items do you have: ");
int items=inputcashier.nextInt();
for (int i = 0; i < items; i++) {
cus1.data();
cus1.ShowData();
total=total+total;
}
System.out.println("Your grand total is: "+total);
}
}

The problem states that you need to hold data of multiple types, an object is the best way to hold this data. You would first need to create the SalesRecord.
class SalesRecord{
String itemName;
double unitPrice;
double total;
String status;
// constructor
SalesRecord(String _itemName,double _unitPrice,double _total,String _status){
this.itemName = _itemName;
this.unitPrice = _unitPrice;
this.total = _total;
this.status = _status;
}
}
Once you have created this object the problem then states to store them in an array size 10 called salesRecord
SalesRecord[] salesRecord = new SalesRecord[10];
This array will now hold the SalesRecord objects. Thus has the type SalesRecord rather than your typical int,string or double.
Here's a good intro to creating and storing objects.

Related

Altering Setters and Getters Via User Input

I have tried a few things and I cannot seem to work this out. I'd like to keep a set price for the iPhone object that is defined by the latest user input.
Below is my Main class:
public class Main {
public static void main(String[] args) {
Iphone iphone = new Iphone();
iphone.setPrice();
System.out.println(iphone.getPrice());
}
}
Below is my Iphone class:
import java.util.Scanner;
public class Iphone {
//Class Attributes
private double price;
Scanner userInput = new Scanner(System.in);
//Constructer method
public Iphone(){
this.price = price;
}
//Getter Method
public double getPrice() {
return 0;
}
//Setter Method
public void setPrice() {
System.out.println("Enter a new price: ");
String price = userInput.nextLine();
System.out.println("The price has now been adjusted to " + price);
}
//toString
#Override
public String toString() {
return "Iphone{" +
"price=" + price +
'}';
}
}
Then, when I typed 800 into the console, instead of showing 800, it'll show 0.0, example below of how it prints to the console:
Enter a new price:
800 //what i typed in
The price has now been adjusted to 800
0.0
Now... I know it is because I am returning 0 in the getter method, so what do I return instead to get the desired result, as it's obviously going to print 0.0 but when I type return double userInput for example, that doesn't work. Note: I am still in the beginner stage of learning Java. Thank you in advance for any help given to me.
You need set class variable to input variable as this.price = Double.parseDouble(price)
public void setPrice() {
System.out.println("Enter a new price: ");
String price = userInput.nextLine();
this.price = Double.parseDouble(price);
System.out.println("The price has now been adjusted to " + price);
}
Your getPrice() method should return price field. And in setPrice() method you need to assign field price.

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

I need help creating a new Arraylist from 2 separate Arraylists

I need to populate my totalprices ArrayList but have no idea how. Basically I need to take the prices ArrayList and the quantities ArrayList and multiply them. Then take the values and add them to the totalprices ArrayList. Then find the min and max of the totalprices. I'm pulling my hair out trying to figure this out. Please help. Thanks!
My code:
import java.util.*;
import java.io.*;
public class Project01 {
public static void main(String[] args) {
ArrayList<String> titles = new ArrayList<String>();//Declare the array lists that will be used.
ArrayList<String> types = new ArrayList<String>();
ArrayList<Double> prices = new ArrayList<Double>();
ArrayList<Integer> quantities = new ArrayList<Integer>();
ArrayList<Double> totalprices = new ArrayList<Double>();
int count = 0;//Set the counter to zero.
Scanner in = new Scanner(System.in);//Establish the scanner so user input can be properly read.
String database = getFile(in);//Setting the file name variable from the method below that asks the user for the file's name.
try {
File file = new File(database);
Scanner inputFile = new Scanner(file);
System.out.println();
System.out.println("Product Summary Report");
System.out.println("------------------------------------------------------------");
while (inputFile.hasNextLine()) {
getTitle(titles, inputFile.nextLine());
getQuantity(quantities, inputFile.nextInt());
inputFile.nextLine();
getPrice(prices, inputFile.nextDouble());
inputFile.nextLine();
getType(types, inputFile.nextLine());
System.out.println("Title: " + titles.get(count));
System.out.println(" Product Type: " + types.get(count));
System.out.println(" Price: " + prices.get(count));
System.out.println(" Quantity: " + quantities.get(count));
System.out.println();
count++;
}
System.out.println("-----------------------------------------------------------------");
System.out.println("Total products in database: " + count);
Integer index = getLargestQuantityTitle(quantities);
System.out.println("Largest quantity item : " + titles.get(index) + " (" + types.get(index) + ")");
ArrayList<Double> highestTotalDollarAmount = getTotalprices(quantities, prices);
Double highestTotalDollarAmount = getHighestDollarAmount(totalprices);
System.out.println("Highest total dollar item: $" + highestTotalDollarAmount);
Integer index2 = getSmallestQuantityTitle(quantities);
System.out.println("Smallest quantity item: " + titles.get(index2) + " (" + types.get(index2) + ")");
System.out.println("Lowest total dollar item: ");
System.out.println("-----------------------------------------------------------------");
inputFile.close();
} catch (IOException e) {
System.out.println("There was a problem reading from " + database);
}
in.close();
}
private static String getFile(Scanner inScanner) {
System.out.print("Enter database filename: ");
String fileName = inScanner.nextLine();
return fileName;
}
private static void getTitle(ArrayList<String> titles, String title) { //This method is creating the array list of the titles from the input file.
titles.add(title);
}
private static void getType(ArrayList<String> types, String type) { //This method is creating the array list of the types from the input file.
types.add(type);
}
private static void getPrice(ArrayList<Double> prices, double price) { //This method is creating the array list of the prices from the input file.
prices.add(price);
}
private static void getQuantity(ArrayList<Integer> quantities, int quantity) { //This method is creating the array list of the quantities from the input file.
quantities.add(quantity);
}
private static Integer getLargestQuantityItem(ArrayList<Integer> quantities){ //This method is determining the maximum value within the quantities array list.
return Collections.max(quantities);
}
private static Double getHighestPricedItem(ArrayList<Double> prices){ //This method is determining the maximum price within the prices array list.
return Collections.max(prices);
}
private static Integer getHighestTotalDollarItem(ArrayList<Integer> prices){ //This method is determining the maximum total value, basically the highest quantity of the item multiplied by it's price.
return Collections.max(prices);
}
private static Integer getSmallestQuantityItem(ArrayList<Integer> quantities){ //This method is determining the minimum value within the quantities array list.
return Collections.min(quantities);
}
private static Integer getLargestQuantityTitle(ArrayList<Integer> quantities){
int index = 0;
Integer largestQuantityMainVariable = getLargestQuantityItem(quantities);
for (int i = 0; i < quantities.size(); i++) {
if (quantities.get(i) != null && quantities.get(i).equals(largestQuantityMainVariable)) {
index = i;
break;
}
}
return index;
}
private static Integer getSmallestQuantityTitle(ArrayList<Integer> quantities){
int index2 = 0;
Integer smallestQuantityMainVariable = getSmallestQuantityItem(quantities);
for (int i = 0; i < quantities.size(); i++) {
if (quantities.get(i) != null && quantities.get(i).equals(smallestQuantityMainVariable)) {
index2 = i;
break;
}
}
return index2;
}
private static ArrayList<Double> getTotalprices (List<Integer> quantities, List<Double> prices){
ArrayList<Double> totalprices = new ArrayList<Double>();
for (int i = 0; i < quantities.size(); i++) {
totalprices.add(quantities.get(i) * prices.get(i));
}
return totalprices;
}
private static Double getHighestDollarAmount(ArrayList<Double> totalprices){ //This method is determining the maximum price within the prices array list.
return Collections.max(totalprices);
}
}
Output should look like:
Enter database filename: proj1_input.txt
Product Summary Report
------------------------------------------------------------
Title: The Shawshank Redemption
Product Type: DVD
Price: 19.95
Quantity: 100
Title: The Dark Knight
Product Type: DVD
Price: 19.95
Quantity: 50
Title: Casablanca
Product Type: DVD
Price: 9.95
Quantity: 137
Title: The Girl With The Dragon Tattoo
Product Type: Book
Price: 14.95
Quantity: 150
Title: Vertigo
Product Type: DVD
Price: 9.95
Quantity: 55
Title: A Game of Thrones
Product Type: Book
Price: 8.95
Quantity: 100
-----------------------------------------------------------------
Total products in database: 6
Largest quantity item: The Girl With The Dragon Tattoo (Book)
Highest total dollar item: $[1995.0, 997.5, 1363.1499999999999, 2242.5, 547.25, 894.9999999999999]
Smallest quantity item: The Dark Knight (DVD)
Lowest total dollar item: Vertigo ($547.25)
-----------------------------------------------------------------
Input File (.txt file):
The Shawshank Redemption
100
19.95
DVD
The Dark Knight
50
19.95
DVD
Casablanca
137
9.95
DVD
The Girl With The Dragon Tattoo
150
14.95
Book
Vertigo
55
9.95
DVD
A Game of Thrones
100
8.95
Book
Edited to include knutknutsen's answer in the comments below as well as an example implementation for the OP.
Have you considered using a HashMap for this? A HashMap is a List Object that stores 2 objects inside of it. In the below example code, I will be using a String as the "Key" (which will be the title of the movie being indexed) and a created class called StockInfo as the "Object". Then you only need a reference to the title saved somewhere or passed to the class used.
Something like
public class Project01{
static HashMap<String, StockInfo> movies = new HashMap<String, StockInfo>();
static StockInfo movieWithMaxPrice = new StockInfo();
static StockInfo movieWithMinPrice = new StockInfo();
static StockInfo movieWithMaxQuantity = new StockInfo();
static StockInfo movieWithMinQuantity = new StockInfo();
public static void main(String[] args){
int counter = 0;
Scanner in = new Scanner(System.in);
String database = getFile(in);
try{
File file = new File(database);
Scanner inputFile = new Scanner(file);
System.out.println();
System.out.println("Product Summary Report");
System.out.println("---------------------------------------");
while(inputFile.hasNextLine()){
StockInfo movieInfo = new StockInfo();
getTitle(movieInfo, inputFile.nextLine());
getQuantity(movieInfo, inputFile.nextInt());
inputFile.nextLine();
getPrice(movieInfo, inputFile.nextDouble());
inputFile.nextLine();
getType(movieInfo, inputFile.nextLine());
/**This works because we over-rode the toString
*call that java makes on an object when we try to
*print out the object to the console.
*/
System.out.println(movieInfo);
System.out.println();
/**The last thing we do is save the created
*StockInfo to the saved HashMap
*/
movies.put(movieInfo.getTitle(),movieInfo);
}
System.out.println("------------------------------------");
System.out.println("Total products in database: "+movies.size());
System.out.println("Largest Quantity item: "+movieWithMaxQuantity.getTitle()+" "+movieWithMaxQuantity.getQuantity());
System.out.println("Highest total dollar item: "+movieWithMaxPrice.getTitle()+" $"+movieWithMaxPrice.getPrice());
System.out.println("Smallest Quantity Item: "+movieWithMinQuantity.getTitle()+" "+movieWithMinQuantity.getQuantity());
System.out.println("Lowest total dollar item: "+movieWithMinPrice.getTitle()+" $"+movieWithMinPrice.getPrice());
} catch(IOException e){
System.out.println("There was a problem reading from "+database);
}
}
/**This method will return the fileName that is housing the
*database, which is provided to provided through an in console
*input from the user
*/
private static String getFile(Scanner inScanner){
System.out.print("Enter database filename: ");
String fileName = inScanner.nextLine();
return fileName;
}
/**This is a re-written method from the OP code, to read the line
*in the database file and fill the created StockInfo class with
*the title
*/
private static void getTitle(StockInfo si, String lineToRead){
si.setTitle(lineToRead);
}
/**This is a re-written method from the OP code, to read the line
*in the database file and fill the created StockInfo class with
*the quantity. This method also compares the given quantity
*with the saved quantities above Max and Min
*/
private static void getQuantity(StockInfo si, int quantity){
si.setQuantity(quantity);
if(movieWithMaxQuantity.getQuantity()<quantity){
movieWithMaxQuantity = si;
}
if(movieWithMinQuantity.getQuantity()>quantity){
movieWithMinQuantity = si;
}
}
/**This is a re-written method from the OP code, to read the line
*in the database file and fill the created StockInfo class with
*the price. This method also compares the given price with the
*max and min StockInfo objects saved at the top of the class,
*to see if this is higher or lower then those. If it is
*then is saves the new StockInfo object at its respective place
*so that we always have a pointer towards the max and min
*/
private static void getPrice(StockInfo si, double price){
si.setPrice(price);
if(movieWithMaxPrice.getPrice()<price){
movieWithMaxPrice = si;
}
if(movieWithMinPrice.getPrice()>price){
movieWithMinPrice = si;
}
}
/**This is a re-written method from the OP code, that takes the
*next line in the database and assigns it to the StockInfo as
*its type
*/
private static void getType(StockInfo si, String lineToRead){
si.setType(lineToRead);
}
}
/**This is the created class that will be used with the information
*that gets provided
*/
class StockInfo{
private String title = ""; //saved reference to the title
private String type = ""; //saved reference to the type
/**saved reference to the price, pre filled at -1 to avoid null pointer exception*/
private double price = -1;
/**saved reference to the quantity available, pre filled at -1 to avoid null pointer exception*/
private int quantity = -1;
/**This is the constructor, which needs nothing in this case*/
public StockInfo(){}
/**This is the setter for our saved title string above*/
public void setTitle(String title){
this.title=title;
}
/**This is the setter from our saved type string above*/
public void setType(String type){
this.type=type;
}
/**This is the setter for our saved price integer above*/
public void setPrice(double price){
this.price=price;
}
/**This is the setter for our saved quantity integer above*/
public void setQuantity(int quantity){
this.quantity=quantity;
}
/**This is the getter for the title*/
public String getTitle(){
return this.title;
}
/**This is the getter for the type*/
public String getType(){
return this.type;
}
/**This is the getter for the saved price*/
public double getPrice(){
return this.price;
}
/**This is the getter for the saved quantity*/
public int getQuantity(){
return this.quantity;
}
/**Overriding the toString call and making it return the info needed*/
#Override
public String toString(){
return "Title: "+title+" Type: "+type+" Price: "+price+" Quantity: "+quantity;
}
}
If you want to multiply corresponding elements in two lists, you do it the obvious way. There are no tricks involved.
for(int k = 0; k < prices.size(); k++) {
totalprices.add(prices.get(k) * quantities.get(k));
}
Like the answer of #immibis already said, there is no magic multiplying two lists (assuming same length). But I would suggest you to rethink your approach:
Instead of maintaining several list you should create a single class which represents a stock item. With that, you only have to maintain one list.
Like this:
public class Project {
public static class StockItem {
public String name;
public double price;
public int quantity;
// ....
}
public static void main(String[] args) {
List<StockItem> stockList = new ArrayList<>(); // <> works with Java 7+
// make new items
StockItem newItem = new StockItem();
newItem.name = nameFromInput;
newItem.price = priceFromInput;
// etc.
// adding it to list
stockList.add(newItem);
List<Double> totalPrices = computeTotalPrices(stockList);
}
public static List<Double> computeTotalPrices(List<StockItem> stockList) {
List<Double> totals = new ArrayList<>();
for (StockItem item : stockList) {
total.add(item.quantity * item.price);
}
return totals;
}
This should make it easier for you to maintain the context of items, prices, quantities etc.
Note that the class in my code has much room for improvement (or rather design flaws), but it will do the trick. Anything more and you would need more knowledge about designing classes etc. And I'm not sure if you already have that. (if you have, I can revise my answer ;D)
the most elegant solution as I think is
public class Order {
public String name;
public double price;
public int quantity;
public double getTotal(){
return price*quantity;
}
}
public class ReportProvider {
public double getMin(List<Order> orders){
double min = double.MaxValue;
for(Order order : orders) {
double total = order.getTotal();
if(total < min) // same in max just use > instead
{
min = total;
}
}
return min;
}
}

string whitespace throwing errors in a object array

i am trying to enter a book title "hoopa doopa"into my object array. when i try it throws a java.util.InputMismatchException.If i enter a string that has no spaces like"hoopa" the code will run fine all of the way through. What is causing this and how can I fix it? please help thanks
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int counter = 0;
int numberOfProducts=0; //variable for when the user is asked to enter input the number of products to be entered
do { //this will validate the user input
System.out.println("How many products would you like to enter");
while (!input.hasNextInt()) {
System.out.println("That's not a number!");
input.next(); // this is important!
}
numberOfProducts = input.nextInt();
} while (numberOfProducts <= 0);
//end of the do while loop
Products[] products;
products = new Products[numberOfProducts+4];//create a array the size of the user input that was gathered
for (int i=0;i<numberOfProducts;i++)
{
products[i+4]= new Products(); // create each actual Person
System.out.println("What is the product #: ");
products[i+4].setItemNumber(input.nextInt());
System.out.println("What is the book name: ");
products[i+4].setNameOfProduct(input.next());
System.out.println("How many are in stock: ");
products[i+4].setUnitsInStock(input.nextInt());
System.out.println("What is the cost of the Item: ");
products[i+4].setPrice(input.nextDouble());
counter++;
}
products[0] = new Products(0001,"The Red Rose",1,29.99);
products[1] = new Products(0002,"The Bible",3,11.99);
products[2] = new Products(0003,"End of the Programm",2,29.99);
products[3] = new Products(0004,"WHAT!!! the....",1,129.99);
//____________________________________________________________4 products that are already made
for (int i=0;i<numberOfProducts+4;i++)
{
System.out.println(products[i].toString());
input.nextLine();
}
}
}
this is the other class
import java.text.NumberFormat;
public class Products
{
private int itemNumber;
private String nameOfProduct;
private int unitsInStock;
private double unitPrice;
public Products()
{
itemNumber = 0;
nameOfProduct = null;
unitsInStock = 0;
unitPrice = 0.0;
}
public Products(int num,String name,int inStock,double price)
{
itemNumber = num;
nameOfProduct = name;
unitsInStock = inStock;
unitPrice = price;
}
public int getItemNumber()
{
return itemNumber;
}
public void setItemNumber(int newValue)
{
itemNumber=newValue;
}
//----------------------------------------------
public String getNameOfProduct()
{
return nameOfProduct;
}
public void setNameOfProduct(String newValue)
{
nameOfProduct=newValue;
}
//----------------------------------------------
public int getUnitsInStock()
{
return unitsInStock;
}
public void setUnitsInStock(int newValue)
{
unitsInStock = newValue;
}
//-----------------------------------------------
public double getPrice()
{
return unitPrice;
}
public void setPrice(double newValue)
{
unitPrice = newValue;
}
//_______________________________________________
public double calculateTotalItemValue() //method that uses quantity on hand and price part3 1.A
{
return getUnitsInStock()* getPrice();
}//end of method
#Override
public String toString()
{
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
return"\nItem Number: "+getItemNumber() +
"\nItem Name: "+getNameOfProduct()+
"\nItem Quantity: " +getUnitsInStock()+
"\nItemPrice:" +currencyFormat.format(getPrice())
+"\nValue of Inventory: " +currencyFormat.format(this.calculateTotalItemValue());//part3 1.B
}
}
The Scanner sees the space in the book name as a delimiter since you are using the next() method. So when you go to read the nextInt() for the stock amount, the Scanner index is after the space in the book name String, and pulls in the remaining String data, which doesn't convert to an int. Instead, try something like this:
System.out.println("What is the book name: ");
input.nextLine();
products[i+4].setNameOfProduct(input.nextLine());
If you do not add the input.nextLine();, then it will appear as though the book name prompt gets skipped.
Scanner input = new Scanner(System.in);
Actually you are using scanner to get input and by default scanner delimiter is space. So you have to change the default delimiter of your code.
I think this is your problem:
products[i+4].setNameOfProduct(input.next());
What input.next() does is it reads the input from the user, until it reaches white space (the space between hoopa doopa). The function then passes hoopa to the setNameOfProduct method, and then passes doopa to the nextInt function, which gives a runtime error.
To fix your problem I would code
products[i+4].setNameOfProduct(input.nextLine());
Edit:
nextLine() function passes all characters up to the carriage return
Problem :
products[i+4].setNameOfProduct(input.next());
Solution 1 :
Just create another Scanner object for reading input with spaces
Scanner sc1=new Scanner(System.in);
products[i+4].setNameOfProduct(sc1.nextLine());
Solution 2 :
Or to use same scanner object
input.nextLine(); //Include this line before getting input string
products[i+4].setNameOfProduct(input.nextLine());

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

Categories

Resources