I have a program where I want to input a fake stock symbol, number of shares, and price per share. I want the user to be able to search the arraylists of stocks, and if a certain stock is found, the LIFO average price of the last 250 stocks bought is displayed. The user should be able to input a stock more than once, for example
AAPL 50 99.99
and
AAPL 300 50.00
So if the user bought 50 shares at 99.99 and 300 shares at 50.00, it should average the last 250 bought stocks using the correct prices.
Here is where I am so far, I'm having trouble with searching the hashmap and then displaying the average of that certain stock.
package stocks;
import java.util.*;
public class Stocks {
private String sym;
private List<Purchase> purchases;
public Stocks(final String symbol) {
this.sym = symbol;
purchases = new ArrayList<Purchase>();
}
public void addPurchase(final int amt, final double cost){
purchases.add(new Purchase(amt,cost));
}
public String getSym(){
return sym;
}
public void setSym(){
this.sym = sym;
}
public double getAvg250() {
int i = 0;
int total = 0;
int shares = 0;
while (i < purchases.size()) {
Purchase p = purchases.get(i);
if (shares + p.getAmt() >= 250) {
total += (250 - shares) * p.getCost();
shares = 250;
break;
}
shares += p.getAmt();
i++;
}
return total * 1.0 / shares;
}
class Purchase {
private int amt;
private int cost;
public Purchase(int amt, double cost){
}
public int getAmt() {
return amt;
}
public void setAmt(int amt) {
this.amt = amt;
}
public int getCost() {
return cost;
}
public void setCost(int cost) {
this.cost = cost;
}
}
public static void main(String[] args) {
int choice = 0;
while (choice == 0){
System.out.println("Enter 1 to input a new stock, or 2 to query a stock's price, 3 to quit: ");
Scanner sc1 = new Scanner (System.in);
choice = sc1.nextInt();
if(choice==1){
ArrayList<Stocks> StocksList = new ArrayList<Stocks>();
Scanner sc2 = new Scanner (System.in);
System.out.println("Please enter the stock symbol: ");
String sym = sc2.next();
System.out.println("Please enter the number of shares: ");
int amt = sc2.nextInt();
System.out.println("Please enter the price per share: ");
double cost = sc2.nextDouble();
Map<String, Stocks> stocks = new HashMap<String, Stocks>();
Stocks s = stocks.get(sym);
if (s == null) {
s = new Stocks(sym);
stocks.put(sym, s);
}
s.addPurchase(amt, cost);
StocksList.add(s);
}
choice = 0;
if (choice == 2){
Scanner sc3 = new Scanner (System.in);
System.out.println("Please enter the symbol of the stock you wish to see: ");
String search = sc3.next();
}
if(choice==3){
System.exit(0);
}
}
}
}
If you want to iterate over the HashMap you can do below. Thouhg I am not clear about your question totally
Map<String, Stocks> stocks = new HashMap<String, Stocks>();
for (Object key : stocks.keySet()) {
System.out.println("Key : " + key.toString() + " Value : "
+ stocks.get(key));
}
Or you can do
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
UPDATE
you can do something like below
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
if( pairs.getKey() != null && pairs.getKey().equals(sym)) {
pairs.getValue() // this is the cost for share. write logic here to find the last 259 shares and calculate avg
}
}
Related
See the purchase method below where the error occurs
public class StockMain {
public static void main (String[] args){
Scanner console = new Scanner (System.in);
// first stock
System.out.println("First stock symbol:");
String symbol1 = console.next();
Stock stock1 = new Stock (symbol1);
System.out.println("How much shares do you want to purchase?");
int units = console.nextInt();
System.out.println(" What is the price per share?");
double shareprice = console.nextDouble();
double profit1 = stock1.purchase(units,shareprice);
}
}
I just saw the error actually. The method returned nothing and I was assigning it to a variable.
public class Stock {
// This class represents a common stock on the market.
private String symbol;
private int totalShares;
private double totalCost;
// constructors begin here
// pre: Stock != null
public Stock (String theSymbol){
// initialise stock with no shares purchased
if (theSymbol == null) throw new NullPointerException();
symbol = theSymbol;
totalShares = 0;
totalCost = 0.0;
}
// methods begin here
public double getProfit(double currentPrice){
// return the total price of the stock.
if (currentPrice < 0 ) throw new IllegalArgumentException();
return totalShares * currentPrice - totalCost;
}
public void purchase (int shares, double pricePerShare){
// records the purchase units and prices of shares
if (pricePerShare < 0 || shares < 0) throw new IllegalArgumentException();
totalShares += shares;
totalCost += pricePerShare * shares;
}
public String getSymbol(){
return symbol;
}
}
Everything works so far in my program but I'm having trouble with this section of my code:
else if(input.equals("2")) {
System.out.println("Enter the stock symbol:");
symbol2 = in.next();
System.out.println("Enter the number of shares you wish to sell:");
sellshares = in.nextInt();
String tempsymbol = "";
for(int i=0; i<array1.size(); i++) {
tempsymbol = (array1.get(i)).getSymbol();
if(symbol2.equals(tempsymbol)) {
System.out.println("The dollar cost averaged price per share (LIFO): " + (array1.get(i)).averageCost(sellshares));
System.out.println("The dollar cost averaged price per share (FIFO): " + (array2.get(i)).averageCost(sellshares));
}
}
}
It'll go through the loop but tempsymbol will always = "". Why doesn't array1 return anything?
Here's all my code. Apologies ahead of time if any parts are redundant or messy.
import java.util.*;
public class Whoop {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = "";
String symbol = "";
String name = "";
int shares = 0;
double price = 0;
String symbol2 = "";
int sellshares = 0;
int rolling = 0;
stack theStack = null;
queue theQ = null;
String loopcheck = "1";
ArrayList<stack> array1 = new ArrayList<stack>();
ArrayList<queue> array2 = new ArrayList<queue>();
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine();
in.nextLine();
System.out.println("Enter the stock name:");
name = in.nextLine();
System.out.println("Enter the number of shares bought:");
shares = in.nextInt();
System.out.println("Enter the price per share when purchased");
price = in.nextDouble();
theStack = new stack(symbol,name,shares,price);
theQ = new queue(symbol,name,shares,price);
System.out.println("Press 1 to continue entering new shares or press 2 to finish input for " + theStack.getName());
rolling = in.nextInt();
while(rolling == 1) {
System.out.println("Enter the number of shares bought:");
shares = in.nextInt();
System.out.println("Enter the price per share when purchased");
price = in.nextDouble();
theStack.bigPush(shares, price);
theQ.bigAdd(shares, price);
System.out.println("Press 1 to continue entering new shares or press 2 to finish input for " + theStack.getName());
rolling = in.nextInt();
}
array1.add(theStack); //I added the objects after all the values were finalized
array2.add(theQ);
}
else if(input.equals("2")) {
System.out.println("Enter the stock symbol:");
symbol2 = in.next();
System.out.println("Enter the number of shares you wish to sell:");
sellshares = in.nextInt();
String tempsymbol = "";
for(int i=0; i<array1.size(); i++) {
tempsymbol = (array1.get(i)).getSymbol();
if(symbol2.equals(tempsymbol)) {
System.out.println("The dollar cost averaged price per share (LIFO): " + (array1.get(i)).averageCost(sellshares));
System.out.println("The dollar cost averaged price per share (FIFO): " + (array2.get(i)).averageCost(sellshares));
}
}
}
else {
System.out.println("Input invalid ):");
System.exit(0);
}
System.out.println("Press 1 to continue working with your stocks or press anything else to finish up");
loopcheck = in.next();
}
System.out.println("END");
}
}
This is my queue class which works perfectly fine.
import java.util.LinkedList;
public class queue<E> {
private LinkedList<Double> linklist;
private String symbol;
private String name;
private int shares;
private Double price;
public queue(String symbol2, String name2, int shares2, Double price2) {
linklist = new LinkedList<Double>();
shares = shares2;
price = price2;
symbol = symbol2;
name = name2;
bigAdd(shares, price);
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public void add(Double e) {
linklist.add(e);
}
public Double take() {
return linklist.poll();
}
public void bigAdd (int shares2, Double price2) {
while(shares2>0) {
linklist.add(price2);
shares2--;
}
}
public double averageCost(int shares2) {
double average = 0;
int sizer = 0;
while(sizer < shares2) {
average = average + linklist.poll();
sizer++;
}
average = average/shares2;
return average;
}
And this is my stack class which also works fine.
import java.util.*;
public class stack {
private ArrayList<Double> stackArray = new ArrayList<Double>();
private int top;
private String symbol;
private String name;
private int shares;
private Double price;
public stack(String symbol2, String name2, int shares2, Double price2) {
symbol = symbol2;
name = name2;
shares=shares2;
price=price2;
top = -1;
bigPush(shares, price);
}
public double averageCost(int shares2) {
double average = 0;
int sizer = shares2;
while(sizer > 0) {
average = average + stackArray.get(top--);
sizer--;
}
average = average/shares2;
return average;
}
public void push(Double value) {
stackArray.add(++top, value);
}
public Double pop() {
return stackArray.get(top--);
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public void bigPush(int shares2, Double price2) {
while(shares2>0) {
stackArray.add(++top, price2);
shares2--;
}
}
public static void main(String[] args) {
stack theStack = new stack("Dave", "Franco", 2,10.0);
theStack.bigPush(2,20.0);
System.out.println(theStack.getSymbol());
}
}
Also heres an example of my output:
Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold
1
Enter the stock symbol:
DAVE
Enter the stock name:
FRANCO
Enter the number of shares bought:
5
Enter the price per share when purchased
5
Press 1 to continue entering new shares or press 2 to finish input for FRANCO
2
Press 1 to continue working with your stocks or press anything else to finish up
1
Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold
2
Enter the stock symbol:
DAVE
Enter the number of shares you wish to sell:
1
//AND THEN NOTHING HERE WHEN IT SHOULD RETURN AVERAGECOST()
Press 1 to continue working with your stocks or press anything else to finish up
Following your long code,
tt looks like it all boils down to a wrong usage of the Scanner class :
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine(); // problem here
in.nextLine();
this assigns an empty String to symbol, because it consumes the end of line of the previous in.next().
If you change it to :
while(loopcheck.equals("1")) {
System.out.println("Press 1 to enter a new stock or press 2 to find the LIFO and FIFO dollar cost average for the number of shares sold");
input = in.next();
in.nextLine();
if(input.equals("1")) {
System.out.println("Enter the stock symbol:");
symbol = in.nextLine();
it will work.
Edit :
It looks like you are aware of the need to sometimes call in.nextLine() without using its returned value, but you put in.nextLine() in the wrong place.
Im trying to get different variables from loan but none of them ever get to loan.java. My inheritance goes from Loan.Java > BusinessLoan.java > CreateLoan.java. I can get a variable from CreateLoan to display in business but when I set it in business I can't grab it. And I know some of this stuff is stupid but this is my final so some of the stuff was required. Heres my code
Loan.java
package Construction;
public class Loan implements LoanConstant{
public static int loanNumber;
public static String lastName;
public static int loanAmount;
public static int interestRate;
public static int term;
public int primeRate;
public int getLoanNumber() { return loanNumber; }
public void setLoanNumber(int n) { n = loanNumber; }
public String getLastName() { return lastName; }
public void setLastName(String s) { s = lastName; }
public int getLoanAmount() { return loanAmount; }
public void setLoanAmount(int n) {
n = loanAmount;
if (loanAmount > MAX_LOAN_AMOUNT)
loanAmount = MAX_LOAN_AMOUNT;
}
public int getTerm() { return term; }
public void setTerm(int n) {
n = term;
if (term == 1) {
term = SHORT_TERM;
} else if (term == 3) {
term = MEDIUM_TERM;
} else if(term == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public int getInterestRate() { return interestRate; }
public void setInterestRate(int i) { i = interestRate; }
public static void displayAll() {
System.out.println("The Company's Name is " + COMPANY_NAME);
System.out.println("The loan number is " + loanNumber);
System.out.println("The last name on the loan is " + lastName);
System.out.println("The loan amount is " + loanAmount);
System.out.println("The interest rate on the loan is " + interestRate);
System.out.println("The term on the account is " + term);
}
}
PersonalLoan.java
package Construction;
public class PersonalLoan extends Loan{
public PersonalLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.02) + primeRate);
setInterestRate(interestRate);
}
}
BusinessLoan.java
package Construction;
public class BusinessLoan extends Loan{
public BusinessLoan(int ln, String last, int la, int term) {
setLoanNumber(ln);
setLastName(last);
setLoanAmount(la);
setTerm(term);
interestRate = (int)((primeRate * 0.01) + primeRate);
setInterestRate(interestRate);
}
}
CreateLoan.java
package Construction;
import java.util.Scanner;
public class CreateLoan {
public static void main(String[] args) {
int x = 0;
int primeRate;
String type;
Scanner input = new Scanner(System.in);
Loan[] loans = new Loan[5];
System.out.println("Please enter the prime interest rate");
primeRate = input.nextInt();
primeRate = primeRate/100;
input.nextLine();
for(x = 0; x < 6; ++x) {
System.out.println("Please enter a loan type. Choose either Business or Personal. If you don't type it like that you'll get an error.");
type = input.nextLine();
if (type.equalsIgnoreCase("Business")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new BusinessLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
}
else if (type.equalsIgnoreCase("Personal")) {
System.out.println("What is the account number on the loan?");
int ln = input.nextInt();
System.out.println("What is the last name on the account?");
String last = input.nextLine();
input.nextLine();
System.out.println("What is the loan amount? If you put more then 100k it'll only accept up to 100k");
int la = input.nextInt();
System.out.println("What is the term on the account? If you enter something other then 1, 3, or 5 it will default to a short term.");
int term = input.nextInt();
loans[x] = new PersonalLoan(ln, last, la, term);
System.out.println("The Company's Name is " + Loan.COMPANY_NAME);
System.out.println("The loan number is " + loans[x].getLoanNumber());
System.out.println("The last name on the loan is " + loans[x].getLastName());
System.out.println("The loan amount is " + loans[x].getLoanAmount());
System.out.println("The interest rate on the loan is " + loans[x].getInterestRate());
System.out.println("The term on the account is " + loans[x].getTerm());
} else {
System.out.println("You've entered an invalid type. Please restart and try again.");
System.exit(0);
}
}
}
}
LoanConstants.java
package Construction;
public interface LoanConstant {
public final static int SHORT_TERM = 1;
public final static int MEDIUM_TERM = 3;
public final static int LONG_TERM = 5;
public final static String COMPANY_NAME = "Sanchez Construction";
public final static int MAX_LOAN_AMOUNT = 100000;
}
In addition to the Loan fields being static (remove the static). You should also update your setters.
public void setLoanNumber(int n) { n = loanNumber; }
public void setLastName(String s) { s = lastName; }
You are assigning the value to the passed in variable (not the field). Should be
public void setLoanNumber(int n) { loanNumber = n; }
public void setLastName(String s) { lastName = s; }
and
public void setTerm(int n) {
// n = term;
if (n == 1) {
term = SHORT_TERM;
} else if (n == 3) {
term = MEDIUM_TERM;
} else if (n == 5) {
term = LONG_TERM;
} else
term = SHORT_TERM;
}
public void setInterestRate(int i) { interestRate = i; }
Hey guys just need help on how to finish this up.
Code Snippet:
import java.util.Scanner;
public class CreateLoans implements LoanConstants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//set the program here
float prime;
float amountOfLoan = 0;
String customerFirstName;
String customerLastName;
String LoanType;
System.out.println("Please Enter the current prime interest rate");
prime = sc.nextInt() / 100f;
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
LoanType = sc.next();
//enter the Loan amount
System.out.println("Enter the amount of loan");
amountOfLoan = sc.nextInt();
//enter Customer Names
System.out.println("Enter First Name");
customerFirstName = sc.next();
System.out.println("Enter Last Name");
customerLastName = sc.next();
//enter the term
System.out.println("Enter the Type of Loan you want. 1 = short tem , 2 = medium term , 3 = long term");
int t = sc.nextInt();
}
}
I need to display the records I have asked and store the object into an array.
so this where I'm stuck. I need to do this in a loop 5 times and by the end display all records in an array, if that makes sense?
Try this way :
import java.util.Scanner;
public class CreateLoans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Loan[] loans = new Loan[5];
for(int i=0;i<5;i++) {
loans[i] = new Loan();
System.out.println("Please Enter the current prime interest rate");
float prime = sc.nextInt();
prime = (float)(prime/100f);
loans[i].setPrime(prime);
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
String loanType = sc.next();
loans[i].setLoanType(loanType);
//enter the Loan amount
System.out.println("Enter the amount of loan");
float amountOfLoan = sc.nextFloat();
loans[i].setAmountOfLoan(amountOfLoan);
//enter Customer Names
System.out.println("Enter First Name");
String customerFirstName = sc.next();
loans[i].setCustomerFirstName(customerFirstName);
System.out.println("Enter Last Name");
String customerLastName = sc.next();
loans[i].setCustomerLastName(customerLastName);
}
//Display details
for(int i=0;i<5;i++) {
System.out.println(loans[i]);
}
}
}
class Loan {
private float prime;
private float amountOfLoan = 0;
private String customerFirstName;
private String customerLastName;
private String LoanType;
public float getPrime() {
return prime;
}
public void setPrime(float prime) {
this.prime = prime;
}
public float getAmountOfLoan() {
return amountOfLoan;
}
public void setAmountOfLoan(float amountOfLoan) {
this.amountOfLoan = amountOfLoan;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public String getLoanType() {
return LoanType;
}
public void setLoanType(String loanType) {
LoanType = loanType;
}
#Override
public String toString() {
return "First Name : " + customerFirstName + "\n" +
"Last Name : " + customerLastName + "\n" +
"Amount of Loan : " + amountOfLoan + "\n" +
"Loan type : " + LoanType + "\n" +
"Prime : " + prime + "\n\n";
}
}
Create a Loan class and put all necessary details as private members into it and override toString() method.
Make a ArrayList and add all the variables inside that list
ArrayList arrlist = new ArrayList();
arrlist.add(prime);
arrlist.add(LoanType);
arrlist.add(amountOfLoan);
arrlist.add(customerFirstName );
arrlist.add(customerLastName);
arrlist.add(t);
and display the ArrayList
System.out.println(arrlist);
Example of a loop
int[] nums = new int[5];
String[] names = new String[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("Enter a number: ");
int number = input.nextInt();
// insert into array
nums[i] = number;
System.out.println("Enter a name: ");
String name = input.nextLne();
// insert into array
names[i] = name;
}
Everything you want to be looped 5 times, you can put inside the loop. Whatever values you want to store, you can do that in the loop also.
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))