I am a very amateur student programmer who has made a code that sells a user items and then calculates the tax of that item by asking what state the user lives in. It is a very simple code given my lack of experience with programming. Unfortunately, I made the mistake of writing this code without thinking ahead.
This program is actually my final project for my class. Because of that, there are requirements that I have to meet which I am currently having difficulties with. I have completed almost all of the requirements, but have noticed that some are not yet completed. Some requirements I am missing are...:
1 specialized constructer (I have never understood how to do this efficiently, and am having doubts as to if this is still even possible, given my code)
1 accessor and 2 modifiers (Same thing as constructor, how do I do this correctly with my given code?)
Some sort of formated output using printf (Maybe can be used to round the total price? Too bad I don't fully understand it)
Here is my [extremely inefficient] code itself:
import java.util.Scanner;
public class Tax_Calculator {
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
//variables
double taxPrice = 0;
double totalPrice = 0;
int choice = 0;
double rawCost = 0;
System.out.println("Hello! Welcome to the new 7/11 online ordering device.");
System.out.println("We're low on supplies, so only pick one.");
System.out.println("");
//menu
String [][] menu = {
{"(1) Pizza - $4.99"," (6) Slurpee - $0.79"},
{"(2) Cigarettes - $7.99"," (7) Hotdog - $1.99"},
{"(3) Coffee - $2.99", " (8) Doritos - $2.99"},
{"(4) Mountain Dew - $1.49", " (9) Water - $1.29"},
{"(5) Ice cream - $2.49", " (10) Muffin - $0.99"},
};
//prints menu
for (int e = 0; e < 5; e++)
{
System.out.println(menu[e][0] + "\t"+ menu[e][1]);
System.out.print("");
}
System.out.println("");
System.out.println("Enter the number of the item you want: ");
//user chooses item off of menu
int userInputMenu = in.nextInt();
if (userInputMenu == 1)
{
choice = 1;
System.out.println("You chose the pizza for $4.99.");
rawCost = 4.99;
}
if (userInputMenu == 2)
{
choice = 2;
System.out.println("You chose the cigarettes for $7.99.");
rawCost = 7.99;
}
if (userInputMenu == 3)
{
choice = 3;
System.out.println("You chose the coffee for $2.99.");
rawCost = 2.99;
}
**Continues all the way to userInputMenu == 10**
System.out.println("Now to calculate the tax, please enter the state you are currently in: ");
String userInputState = in.next();
//what state is the user in?
if (userInputState.equals("Alaska") || userInputState.equals("Delaware") || userInputState.equals("Montana") || userInputState.equals("New Hampshire") || userInputState.equals("Oregon"))
{
taxPrice = 0.0;
System.out.println("Luckily, the sales tax in " + userInputState + " is 0, so your final price is " + rawCost);
}
if (userInputState.equals("Colorado"))
{
taxPrice = 0.029;
totalPrice = ((taxPrice * rawCost) + rawCost);
System.out.println("The sales tax in " + userInputState + " is only " + taxPrice);
System.out.println("That means that the total price of your item is "+ totalPrice);
}
**Also continues for all 50 states**
//thank you
System.out.println("");
System.out.println("Thank you for shopping at the new online 7/11.");
System.out.println("Thank you come again.");
}
Just asking for some thorough explinations on how I can meet my missing requirements.
Also, how can I have it so when the user is inputting a state, the program can read it as either "MARYLAND" or "maryland"?
Have you read anything on object oriented programming? This is a great situation to use it, since you have a superclass of 'items', subclasses of those items 'coffee' 'slurpee' etc. Also is the customer able to purchase more than one item at a time and then find the total with tax?
I attempted to code this. You could take it further based on inputs from others on SO or your needs. It could be good start up for you. Add try/catch to handle exceptions:
Class to hold Menu objects:
public class Menu {
private int id;
private String item;
private double Price;
public Menu(int id, String item, double price) {
super();
this.id = id;
this.item = item;
Price = price;
}
public int getId() {
return id;
}
public String getItem() {
return item;
}
public double getPrice() {
return Price;
}
#Override
public String toString() {
return "Menu [id=" + id + ", item=" + item + ", Price=$" + Price + "]";
}
public boolean validateMenu(int id) {
if (id == this.id) {
System.out.println("You chose the " + item + " for " + Price);
return true;
}
return false;
}
}
Class to hold State objects:
public class State {
private String message;
private String state;
private double taxPrice;
public State(String state, double taxPrice, String message) {
this.state = state;
this.taxPrice = taxPrice;
this.message = message;
}
public String getMessage() {
return message;
}
public String getState() {
return state;
}
public double getTaxPrice() {
return taxPrice;
}
#Override
public String toString() {
return "State [taxPrice=" + taxPrice + ", state=" + state
+ ", message=" + message + "]";
}
public boolean validateState(String state) {
if (state.equalsIgnoreCase(this.state)) {
System.out.println(this.message.replace("userInputState", this.state) + this.taxPrice);
return true;
}
return false;
}
}
Tax_Calculator
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Tax_Calculator {
public static void main(String[] args) throws Exception {
Scanner in = null;
Tax_Calculator tc;
Menu menu = null;
State state = null;
double taxPrice;
double totalPrice;
System.out
.println("Hello! Welcome to the new 7/11 online ordering device.");
System.out.println("We're low on supplies, so only pick one.");
System.out.println("");
tc = new Tax_Calculator();
boolean continueFlag = true;
while (continueFlag) {
tc.printMenu();
System.out.println("");
System.out.println("Enter the number of the item you want: ");
in = new Scanner(System.in);
int userInputMenu = in.nextInt();
for (Menu menu2 : tc.menuList)
if (menu2.validateMenu(userInputMenu)) {
menu = menu2;
break;
}
if (menu == null)
System.out.println("Please choose a valid number! \n");
else
continueFlag = false;
}
System.out.println("");
System.out
.println("Now to calculate the tax, please enter the state you are currently in: ");
in.nextLine();
String userInputState = in.nextLine();
for (State state2 : tc.stateList)
if (state2.validateState(userInputState)) {
state = state2;
break;
}
taxPrice = state.getTaxPrice();
totalPrice = (1 + taxPrice) * menu.getPrice();
System.out.print("That means that the total price of your item is ");
System.out.printf("%.2f", totalPrice);
System.out.println("");
System.out.println("Thank you for shopping at the new online 7/11.");
System.out.println("Thank you come again.");
in.close();
tc.destroy();
}
private List<Menu> menuList = null;
private List<State> stateList = null;
Tax_Calculator() {
initMenu();
initState();
}
private void destroy() {
menuList = null;
stateList = null;
}
private void initMenu() {
menuList = new ArrayList<Menu>();
menuList.add(new Menu(1, "Pizza", 4.99));
menuList.add(new Menu(2, "Cigarettes", 7.99));
menuList.add(new Menu(3, "Coffee", 2.99));
}
private void initState() {
stateList = new ArrayList<State>();
stateList.add(new State("North Dakota", 0.05,
"The sales tax in userInputState is "));
stateList.add(new State("Arizona", 0.05,
"The sales tax in userInputState is "));
stateList.add(new State("Maine", 0.05,
"The sales tax in userInputState is "));
}
private void printMenu() {
for (Menu menu : menuList)
System.out.println(menu);
}
}
Related
"Write a Java program to simulate an online store. The program should begin
by displaying a list of products and their prices. There should be a minimum of 4
products offered.
My code is below, it works without the strings but I need to have names for the cakes(display names and prices)
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input= new Scanner(System.in)
int cakeNo = 0;
double cake1;
double cake2;
double cake3;
double cake4;
double cake5;
int quantity;
double totalSales = 0;
while(cakeNo !=0 )
System.out.println("Enter cake number 1-5");
cakeNo=input.nextInt();
System.out.println("Enter quantity");
quantity = input.nextInt();
switch (cakeNo){
case 1: cake1 = 3.70;
totalSales+=(3.70*quantity);
break;
case 2: cake2 = 4.20;
totalSales+=(4.20*quantity);
break;
case 3: cake3 = 4.50;
totalSales+=(4.50*quantity);
break;
case 4: cake4 = 5.00;
totalSales+=(5.00*quantity);
break;
case 5: cake5 = 5.50;
totalSales+=(5.50*quantity);
break;
}
System.out.println(totalSales);
}
}
Thank you so much for reading! Please help if you have an idea.
Well there are a few things wrong in your code that you should take care first.
First: The first 5 string are wrongly defined. It should be like this String cake1 = "Angel cake" and so on.
Second: The strings and doubles have the same names you cannot do that. You need to have something like String cake1Name = "Name" and double cake1Price = price this way you have two distinct properties for everycake.
Third: Right now the code doesn't even enters the while loop. Since cakeNo starts with 0 and the condition in your while loop is cakeNo != 0 right on before the first loop this condition will be tested and it will be false meaning that the loop code won't be executed and will jump to the end of the program.
After this fixes there is still a little problem. After you get the input from the user if said input is 0 meaning that he wants to leave the program will still ask him for a quantity. You need to add/change something that breaks the loop when this conditions is true. I don't want to give you code but I hope this answer can help you good luck :)
This is what I would do:
public class Main {
LinkedList<Product> cart = new LinkedList<Product> ();
Scanner scanner = new Scanner(System.in);
double tax = 7.5;
boolean done = false;
public Main() {
cart.add(new Product("Cake 1", 3.70));
cart.add(new Product("Cake 2", 4.20));
cart.add(new Product("Cake 3", 4.50));
cart.add(new Product("Cake 4", 5.00));
cart.add(new Product("Cake 5", 5.50));
}
public void displayCart() {
for (int i = 0; i < cart.size(); i++) {
switch (cart.get(i).quantitySelected){
case 0:
System.out.println(i + ": " + cart.get(i).name + " none selected");
break;
default:
System.out.println(i + ": " + cart.get(i).name + " selected: " + cart.get(i).quantitySelected);
break;
}
}
}
public void addToCart(int product, int amount) {
cart.get(product).select(amount);
}
public void getSelection() {
int productSelected;
System.out.println("enter a product value or FINNISHED to end: ");
try {
productSelected = scanner.nextInt();
} catch (InputMismatchException e) {
done = true;
return;
}
System.out.println("enter amount to select: ");
int amount = scanner.nextInt();
cart.get(productSelected).select(amount);
}
public double getSubtotal() {
double cost = 0.00;
for (Product product : cart) {
cost += product.cost * product.quantitySelected;
}
return cost;
}
public double getTotal() {
return getSubtotal() + getSubtotal()*tax;
}
public void finnishPurchase() {
System.out.println("---------------------");
System.out.println("subtotal: " + getSubtotal());
System.out.println("tax: " + tax);
System.out.println("total: " + getTotal());
}
public static void main(String[] args) {
Main store = new Main();
while (!store.done) {
store.displayCart();
store.getSelection();
}
store.finnishPurchase();
}
}
public class Product {
String name;
double cost;
int quantitySelected = 0;
public Product(String name, double cost) {
this.name = name;
this.cost = cost;
}
public void select(int quantity) {
quantitySelected = quantity;
}
}
Attached is my finalized code for a Lab project. I have everything done but for some reason my code sits idle? I think it may be an issue between the "bank1" and "bank2" objects and the Bank class?
I apologize that the code is so long, as I don not know where the issue is. Help please :(
Currency Exchange Class (main)
import javax.swing.*;
import java.io.FileNotFoundException;
import java.util.*;
public class CurrencyExchange {
public static void main(String [] args) throws FileNotFoundException {
//Create 2 bank objects, one for each file "bank1.txt" & "bank2.txt"
Bank bank1 = new Bank("bank1.txt");
Bank bank2 = new Bank("bank2.txt");
int userCont = 0;
do {
boolean buy = false;
double amount;
int banksSupported = 0;
String currencyCode;
Scanner keyboard = new Scanner(System.in);
String userAnswer;
//Ask user to buy or sell - use continue to repeat loop if invalid
System.out.println("Do you want to buy or sell?");
userAnswer = keyboard.nextLine();
if (!userAnswer.equalsIgnoreCase("buy") && (!userAnswer.equalsIgnoreCase("sell")) ) {
System.out.println("Invalid response. Please enter buy or sell. ");
continue;
}
if (userAnswer.equalsIgnoreCase("buy")) {
buy = true;
}
//Ask user for foreign currency - use continue to repeat loop if invalid
System.out.println("Which currency would you like to use?");
currencyCode = keyboard.nextLine().toUpperCase();
//Check and Print how many banks support the users currency - use continue to repeat loop if none
if(bank1.supportCurrency(currencyCode))
++banksSupported;
if(bank2.supportCurrency(currencyCode))
++banksSupported;
if (banksSupported == 0) {
System.out.println("There are no banks the support " + currencyCode + ". Please enter a different currency.");
continue;
}
else if (banksSupported == 1) {
System.out.println("One bank supports " + currencyCode + ".");
}
else {
System.out.println("Two banks support " + currencyCode + ".");
}
//Prompt the user for the amount of foreign currency and get the user input
System.out.println(" What amount of " + currencyCode + "?");
amount = keyboard.nextDouble();
//Use the quoteBuy or quoteSell methods of the Bank objects to get a Quote from every bank supporting the foreign currency.
//Print the quote(s) from the bank(s), using the toString method of the Quote object(s).
if(buy) {
if (bank1.supportCurrency(currencyCode)) {
System.out.println(bank1.quoteBuy(amount, currencyCode));
}
if (bank2.supportCurrency(currencyCode)) {
System.out.println(bank2.quoteBuy(amount, currencyCode));
}
}
else {
if (bank1.supportCurrency(currencyCode)) {
System.out.println(bank1.quoteBuy(amount, currencyCode));
}
if (bank2.supportCurrency(currencyCode)) {
System.out.println(bank2.quoteBuy(amount, currencyCode));
}
}
//Use the console to prompt the user for another transaction.
userCont = JOptionPane.showConfirmDialog(null, "Would you like to preform another transaction?", "Contniue", JOptionPane.YES_NO_OPTION);
} while(userCont == 0); // while ( the user wants to continue performing transactions )
}
}
Bank Class
import java.io.*;
import java.util.*;
public class Bank {
// Five private data fields: The name of the bank, The commission rate, Three fields for the three currencies exchanged by the bank.
// Each of these should have type Currency.
private String bankName;
private double commissionRate;
private Currency currencyCode1;
private Currency currencyCode2;
private Currency currencyCode3;
public Bank(String fileA) throws FileNotFoundException {
File bankFile = new File(fileA);
Scanner keyboard = new Scanner(System.in);
this.bankName = keyboard.nextLine();
this.commissionRate = Double.parseDouble((keyboard.nextLine()));
this.currencyCode1 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
this.currencyCode2 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
this.currencyCode3 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
keyboard.close();
}
public boolean supportCurrency(String currencyCode) {
return currencyCode.equalsIgnoreCase(currencyCode1.getCurrencyCode())
|| currencyCode.equalsIgnoreCase(currencyCode2.getCurrencyCode())
|| currencyCode.equalsIgnoreCase(currencyCode3.getCurrencyCode());
}
// Working on getRate method.
public double getRate(String currencyCode) {
double bankExchangeRate = -1.0;
if (currencyCode.equalsIgnoreCase(currencyCode1.getCurrencyCode())) {
bankExchangeRate = currencyCode1.getExchangeRate();
}
else if (currencyCode.equalsIgnoreCase(currencyCode2.getCurrencyCode())) {
bankExchangeRate = currencyCode2.getExchangeRate();
}
else if (currencyCode.equalsIgnoreCase(currencyCode3.getCurrencyCode())) {
bankExchangeRate = currencyCode3.getExchangeRate();
}
return bankExchangeRate; //return -1.0
}
public Quote quoteBuy(double amt, String currencyCode) {
double rate = getRate(currencyCode);
Quote quote;
if(rate == -1.0) {
quote = null;
}
else {
double userOwes = amt / (rate * (1 - commissionRate)); // This calculates the commission amount based on the dollar amount.
double commission = userOwes * commissionRate;
quote = new Quote(bankName, "USD", userOwes, currencyCode, amt, commissionRate, commission);
}
return quote;
}
public Quote quoteSell(double amt, String currencyCode) {
double rate = getRate(currencyCode);
Quote quote;
if(rate == -1.0) {
quote = null;
}
else {
double base = amt / rate; // This calculates the dollar value of the foreign currency.
double commission = commissionRate * base; // This calculates the commission amount based on the dollar amount.
double amtConverted = base - commission; // The bank takes a cut.
quote = new Quote(bankName, currencyCode, amt, "USD", amtConverted, commissionRate, commission);
}
return quote;
}
}
Currency Class
public class Currency {
// Two private data fields, one to hold the currency code and one to hold the exchange rate.
// Note that the exchange rate for the same currency could be different for different banks
private final String currencyCode;
private final double exchangeRate;
// A constructor that takes two arguments: the currency code and exchange rate.
// The constructor should assign the private members from the values of the arguments.
public Currency(String currencyCode, double currencyExchangeRate) {
this.currencyCode = currencyCode;
this.exchangeRate = currencyExchangeRate;
}
// An accessor method (getter) for each data field.
public String getCurrencyCode() {
return currencyCode;
}
public double getExchangeRate() {
return exchangeRate;
}
}
Quote Class
import java.text.DecimalFormat;
public class Quote {
private String bankName;
private String codeToBank;
private double amtToBank;
private String codeFromBank;
private double amtFromBank;
private double commissionRate;
private double commissionAmt$;
DecimalFormat decimalFormat;
public Quote(String bankName, String currencyCode, double amt, String usd, double amtConverted, double commissionRate, double commission) {
this.bankName = bankName;
this.codeToBank = currencyCode;
this.amtToBank = amt;
this.codeFromBank = usd;
this.amtFromBank = amtConverted;
this.commissionRate = commissionRate;
this.commissionRate = commission;
this.decimalFormat = new DecimalFormat("0.00");
}
public String toString() {
return (this.bankName + " is willing to offer you " + decimalFormat.format(this.amtFromBank)
+ " " + this.codeFromBank + " for "
+ decimalFormat.format(this.amtToBank) + " "
+ this.codeToBank + ", after collecting a commission of "
+ decimalFormat.format(this.commissionRate)
+ " USD (" + Math.round(100 * this.commissionRate) + "%)");
}
}
Your issue is that your Scanner is reading from System.in, when it should be reading from the input files "bank1.txt" or "bank2.txt".
Change this line in Bank:
Scanner keyboard = new Scanner(System.in);
to this:
Scanner keyboard = new Scanner(bankFile);
And your code will work as intended.
Here is my program. All i'm trying to do is print the ArrayList at the end and it won't, what am i doing wrong I'm trying to use mls.ToString() but thats not working. Please tell me what i did wrong. PS this is homework and thanks for the help.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Book> mls = new ArrayList<Book>();
String userAuthor;
String userTitle;
int userYearPub;
int userPageCount;
String answer;
int numberAnswer;
int choice;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the author of the book.");
userAuthor = in.next();
System.out.println();
System.out.println("Please enter the title of the book.");
userTitle = in.next();
System.out.println();
System.out.println("Please enter the year the book was published.");
userYearPub = in.nextInt();
System.out.println();
System.out.println("Please enter the number of pages of the book.");
userPageCount = in.nextInt();
System.out.println();
Book usersBook = new Book(userAuthor, userTitle, userYearPub, userPageCount);
System.out.println(usersBook.ToString());
System.out.println();
do {
System.out.println("If you want to change anything press one of the following options: ");
System.out.println('1' + " Author.");
System.out.println('2' + " Title.");
System.out.println('3' + " Year it was published.");
System.out.println('4' + " Number of pages");
System.out.println('5' + " Quit");
System.out.println();
choice = in.nextInt();
if (choice == 1) {
System.out.println("Please enter the new author:");
answer = in.next();
usersBook.setAuthor(answer);
}
if (choice == 2) {
System.out.println("Please enter the new title:");
answer = in.next();
usersBook.setTitle(answer);
}
if (choice == 3) {
System.out.println("Please enter the new year:");
numberAnswer = in.nextInt();
usersBook.setYearPub(numberAnswer);
}
if (choice == 4) {
System.out.println("Please enter the new pages count:");
numberAnswer = in.nextInt();
usersBook.setPages(numberAnswer);
}
if (choice == 5) {
break;
}
System.out.println();
System.out.println("Is this correct?");
System.out.println('1' + " yes");
System.out.println('2' + " no");
choice = in.nextInt();
if (choice == 1) break;
}while (choice == 2);
mls.add(usersBook);
System.out.println(usersBook.ToString());
System.out.println();
System.out.println("Do you want to input another book?");
System.out.println("If so press 1, if not press 2.");
choice = in.nextInt();
System.out.println(mls.ToString());
} while (choice == 1);
}
}
Here is the Book class.
public class Book {
private String author;
private String title;
private int yearPub;
private int pages;
public Book(String Author, String Title, int YearPub, int Pages)
{
this.author = Author;
this.title = Title;
this.yearPub = YearPub;
this.pages = Pages;
}
public String ToString()
{
return "The Author of this book is " + author +
"\nThe title of this book is " + title +
"\nThe year published is " + yearPub +
"\nThe number of pages is " + pages;
}
public void setAuthor(String newSring)
{
author = newSring;
}
public void setTitle(String newString)
{
title = newString;
}
public void setYearPub(int newValue)
{
yearPub = newValue;
}
public void setPages(int newValue)
{
pages = newValue;
}
}
mls is not a Book. It is an ArrayList<Book>. You need to fetch the books from the list before calling ToString(). Something like the following:
for(int i = 0; i < mls.size(); i++) {
System.out.println(mls.get(i).ToString());
}
You are triying to access the method ToString of a List of books "mls", which hasn't such method, your variable is not a book is a list of books.
You have to replace "mls.ToString()" for "usersBook.ToString()" in order to access your method.
PS: You should rename your method with lowercase toString, in Java all objects implicitly inherit that method, you can/shall override it.
Problem is line with:
System.out.println(mls.ToString());
ArrayList don't have ToString() method. ArrayList have toString() method.
Solution is:
System.out.println(mls.toString());
or
System.out.println(mls);
You musn't use toString() method, it will be automatically called.
And second problem is that your toString() method in Book class should look like:
#Override
public String toString() {
return "The Author of this book is " + author +
"\nThe title of this book is " + title +
"\nThe year published is " + yearPub +
"\nThe number of pages is " + pages;
}
the question is :
A fruit shop sells several types of fruits each day. Write a program that reads from user several lines of input.Each line includes a fruit's name,price per kilogram (as an integer), number of kilograms sold (as an integer).
the program should calculate and print the earned money of all fruits sold and fruit that achieved largest profit.
hint: -you could assume that user will insert valid data -user could stop the program via entering the word "stop" as a fruit's name.
Sample input and out put:
in each line, insert a fruit's name, price per kilogram, number of kilograms sold. To halt the program,insert "stop" as a fruit's name
banana 2 11
mango 3 8
peach 4 5
stop
the earned money of all fruits sold: 66
fruit that achieved the largest profit: mango
what i wrote now:
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname= " ";
String maxfruit = " ";
int price = 0,number=0;
int sum=0;
int max=0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
if (fruitname.equals("stop"))
{
sum = sum+(price*number);
}
if (max<(price*number))
{
max = price*number;
maxfruit = fruitname;
}
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
the program is not reading what i submit to it, don't know why and not giving me the sum and the max fruit.. what is the problem of what i wrote?
As you can see your reads happen in the while loop:
while (!fruitname.equals("stop"))
{
fruitname = input.next();
price = input.nextInt();
number = input.nextInt();
}
Every time it loops - it overrides the values. Finally when you read stop and exit the loop - your fruitname is stop. So you need to fix your logic on how you would want to read in the input
Working variant:
public class FruitTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
String text = input.nextLine();
String[] words = text.split(" ");
List<Fruit> fruits = parseInput(words);
int sum = getSum(fruits);
String popular = getPopularFruitName(fruits);
System.out.println("Got fruits: " + fruits.toString());
System.out.println("the earned money of all fruits is " + sum);
System.out.println("fruit that achieved the largest profit is " + popular);
}
private static String getPopularFruitName(List<Fruit> fruits) {
int max = 0;
String name = null;
for (Fruit fruit : fruits) {
int checkVal = fruit.getPrice() * fruit.getAmount();
if(checkVal > max) {
max = checkVal;
name = fruit.getName();
}
}
return name;
}
private static int getSum(List<Fruit> fruits) {
int result = 0;
for (Fruit fruit : fruits) {
result += fruit.getPrice() * fruit.getAmount();
}
return result;
}
private static List<Fruit> parseInput(String[] words) {
List<Fruit> result = new ArrayList<Fruit>();
int element = 1;
final int name = 1;
final int price = 2;
final int amount = 3;
Fruit fruit = null;
for (String word : words) {
if (word.equals("stop") || word.isEmpty()) {
break;
}
if(element > amount)
element = name;
switch (element) {
case name:
fruit = new Fruit(word);
result.add(fruit);
break;
case price:
if (fruit != null) {
fruit.setPrice(Integer.valueOf(word));
}
break;
case amount:
if(fruit != null) {
fruit.setAmount(Integer.valueOf(word));
}
break;
}
element++;
}
return result;
}
static class Fruit {
String name;
int price = 0;
int amount = 0;
Fruit(String name) {
this.name = name;
}
String getName() {
return name;
}
int getPrice() {
return price;
}
void setPrice(int price) {
this.price = price;
}
int getAmount() {
return amount;
}
void setAmount(int amount) {
this.amount = amount;
}
#Override
public String toString() {
return name + ". $" + price +
", amount=" + amount;
}
}
}
Comments to code - it's proper way to parse all the inputted string and parse it to an object that stores all the data - name, price and amount. Store all parsed objects into array or a list and then calculate max and popular fruit while looping your parsed fruit array
I found some mistake. The most important was in the while condition. Check this out.
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner (System.in);
String fruitname = null;
String maxfruit = null;
int fruitSum = 0;
int totalSum = 0;
int max = 0;
System.out.print("Fruit name, " + "price in killogram, number of killogram sold: ");
while(!(fruitname = input.next()).equals("stop")){
fruitSum = input.nextInt() * input.nextInt();
totalSum += fruitSum;
if(fruitSum > max){
maxfruit = fruitname;
max = fruitSum;
}
}
System.out.println("the earned money of all fruits is " + totalSum);
System.out.println("fruit that achieved the largest profit is "+ maxfruit);
}
}
Oh it is reading it.
the problem is that it doesn't do what you want it to do.
the problems with the code I can see are this:
you are not storing the fruits quantities or prices anywhere, you need to store the values
in an array or something (maxFruit,MaxValue) to compare them later.
when you are reading the fruit values and a "stop" string is input the next step in your code is to wait for the price so it won't get out of the loop even if you input "stop", you need to restructure your scanner loop.
And if it is a beginner class it may be ok, but the code you are writing is not object oriented don't write the logic in the main.
You may want to learn to debug it is a very useful tool when you are learning to code, if you run this program in debug mode , you could see that the values are getting input and everything that is happening, Netbeans and Eclipse have very good debuggers and it would be worth to expend half an hour learning the basics of debugging It certainly helped me a lot when I was starting.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class FruitSells {
public static void main(String... args) {
BufferedReader bufer = new BufferedReader(new InputStreamReader(System.in));
try {
String str;
String[] inarr;
int sumMoney = 0;
do {
str = (String) bufer.readLine();
inarr = str.split(" ");
for(int i = 1; i < inarr.length; i += 3) {
sumMoney += Integer.parseInt(inarr[i]) * Integer.parseInt(inarr[i + 1]);
}
System.out.println(sumMoney);
sumMoney = 0;
} while (!str.equals("stop"));
} catch(IOException ex) {
System.out.println("Problems with bufer.readLine()");
}
}
}
something like this you can modernize it.sorry for eng i can not speak))and write correctly of course))
There are a few things I would like some help on. First and foremost, when I compile, my product number and price get mixed up. Why? Secondly, why does the product type always return null? I would also like to combine all the message boxes but every attempt I have made fails. If someone could lead me in the right direction, I would appreciate it. Here is my code:
MAIN
package inventory4;
import java.util.Scanner;
import java.util.Arrays; //Needed to include data for arrays
import javax.swing.JOptionPane; //JOptionPane import tool
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ItemDetails theItem = new ItemDetails();
int number;
String Name = "";
String Type = "";
String sNumber = JOptionPane.showInputDialog(null,"How many items are to be put into inventory count?: ");
number = Integer.parseInt(sNumber);
ItemDetails[] inv = new ItemDetails[number];
for (int count = 0; count < inv.length; ++count)
{
Name = JOptionPane.showInputDialog(null,"What is item " + (count + 1) + "'s name?");
theItem.setName(Name);
Type = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product type");
String spNumber = JOptionPane.showInputDialog(null,"Enter " + Name + "'s product number");
double pNumber = Double.parseDouble(spNumber);
theItem.setpNumber(pNumber);
String sUnits = JOptionPane.showInputDialog(null,"How many " + Name + "s are there in inventory?");
double Units = Double.parseDouble(sUnits);
theItem.setUnits(Units);
String sPrice = JOptionPane.showInputDialog(null,Name + "'s cost");
double Price = Double.parseDouble(sPrice);
theItem.setPrice(Price);
inv[count] = new ItemDetails(Name, Price, Units, pNumber);
}
for (int i = 0; i < inv.length; ++i)
{
JOptionPane.showMessageDialog(null, "Product Name: " + inv[i].getName());
//Why can't I use this instead of having multiple boxes?:
//JOptionPane.showMessageDialog(null, "Product Name: \nProduct Type: \nProduct Number: \nUnits in Stock: \nPrice Per Unit: " + inv[i].getName() + inv[i].getUniqueType() + inv[i].getpNumber() + inv[i].getUnits(), + inv[i].getPrice());
JOptionPane.showMessageDialog(null, "Product Type: " + inv[i].getUniqueType());
JOptionPane.showMessageDialog(null, "Product Number: " + inv[i].getpNumber());
JOptionPane.showMessageDialog(null, "Amount of Units in Stock: " + inv[i].getUnits());
JOptionPane.showMessageDialog(null, "Price per Unit: " + inv[i].getPrice());
JOptionPane.showMessageDialog(null, String.format("Total cost for %s in stock: $%.2f", inv[i].getName(), inv[i].calculateTotalPrice()));
JOptionPane.showMessageDialog(null,String.format("Restocking fee for %s is $%.2f", inv[i].getName(), inv[i].calculateRestock()));
String combinedData = inv[i].toString();
if(i == (inv.length -1)){
String lastItem = String.format("\nTotal Cost for all items entered: $%.2f\n", Items.getCombinedCost(inv));
combinedData = combinedData + lastItem; //combine total value to the end of the last object output
JOptionPane.showMessageDialog(null, combinedData); //Show Message
}else{
JOptionPane.showMessageDialog(null, combinedData); //Show Message
}
} //end for
} //end main
} //end class
ITEMS
package inventory4;
public class Items implements Comparable
{
private String Name;
public double pNumber, Units, Price;
String allInfo;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items)item;
return this.getName().compareTo(tmp.getName());
} // end compareTo method
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
public String toString()
{
StringBuffer allInfo = new StringBuffer();
allInfo.append(String.format("Name: %s\n pNumber: %.0f \n Units: %.0f \n Price: %.2f\n",
getName(),getpNumber(),getUnits(),getPrice()));
return allInfo.toString();
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item) //This is used to set up the method
{
double combined = 0; //Loops through array after array is complete
for (int i = 0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice(); //Sets up to combine all TotalPrice
//calculations in array
} //end loop
return combined;
} //end method
} //end class
ITEM DETAILS
package inventory4;
public class ItemDetails extends Items
{
private String UniqueType;
public ItemDetails()
{
super();
}
public ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice)
{
super(productName,productNumber,unitsInStock,unitPrice);
}
public String enterUniqueType()
{
return UniqueType;
}
public String setUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
public double calculateRestock() //setting up to calculate the restocking fee at 5%
{
return (Price * .05);
}
}
// getter???
public String setUniqueType() {
return UniqueType;
}
should be:
//setter
public void setUniqueType(String type) {
UniqueType = type;
}
and
inv[count] = new ItemDetails(Name, Price, Units, pNumber);
should be:
inv[count] = new ItemDetails(Name, pNumber, Units,Price );//look at the order
inv[count].setUniqueType(Type);//you have not set it.
I would also like to combine all the message boxes…
As an example, see JOptionPaneTest.
First and foremost, when I compile, my product number and price get mixed up. Why?
You're creating a new ItemDetails object with the call to
new ItemDetails(Name, Price, Units, pNumber);
but your constructor for ItemDetails is
ItemDetails(String productName, double productNumber, double unitsInStock, double unitPrice)
i.e., it takes the product number first and price last, not the other way around
Secondly, why does the product type always return null?
You're never actually setting your type, both your set and get methods do the same thing! That the setter is returning a value should've been a warning!
public String setUniqueType()
{
return UniqueType;
}
public String getUniqueType()
{
return UniqueType;
}
This is what it should be
public void setUniqueType(String type)
{
this.UniqueType = type;
}