Searching through arraylists for the largest number - java

So I'm currently making a code right now that searches through arraylists and prints out the largest one. This code prompts the user for BankAccount names and how much money the account has. Currently I've run into the problem of not knowing how to search through arraylists for the biggest number. I also don't know how to compare each balance to the maxBalance. Any help is appreciated, Thanks.
import java.io.*;
import java.util.*;
import java.text.*;
public class Project43Tester
{
public static void main(String args[])
{
NumberFormat formatter = NumberFormat.getNumberInstance( );
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String name;
ArrayList <String> aryLst = new ArrayList<String>();
do
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Please enter the name to whom the account belongs.(\"Exit\" to abort)");
name = kbReader.nextLine( );
if( !name.equalsIgnoreCase("EXIT") )
{
System.out.print("Please enter the amount of the deposit. ");
double amount = kbReader.nextDouble();
System.out.println(" ");
ArrayList <String> BankAccount = new <String> ArrayList();
AryLst.add(BankAccount);
}
}while(!name.equalsIgnoreCase("EXIT"));
Search aryList and print out the name and amount of the largest bank account
BankAccount ba = //get first account in the list
double maxBalance = ba.balance;
String maxName = ba.name;
for(int j = 1; j < aryLst.size( ); j++)
{
?
? Step through the remaining objects and decide which one has
largest balance (compare each balance to maxBalance)
?
}
System.out.println(" ");
System.out.println("The account with the largest balance belongs to " + maxName + ".");
System.out.println("The amount that the account contains is $" + formatter.format(maxBalance) + ".");
}
}

You will have to traverse the ArrayList. During the traversal of the ArrayList, set the first element as max and compare it with next. If it is greater, then set the new element as the max.

The easiest way is to use ArrayList's sort function. No headache there.
Refer this link

List<String> l = new ArrayList<String>();
l.add("2.33");
l.add("3.45");
l.add("1.11");
Collections.sort(l);
for(String s: l) {
System.out.println(s);
}
Result:
1.11
2.33
3.45

This is a slightly modified version of your code. Would advise to use a Comparable/Comparator for sorting (which you should try; modify below code).
Here's simple traversal through the array iterating and accessing object properties for your example.
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Project43Tester
{
static class BankAccount
{
String name;
Double amount;
public BankAccount(String name, Double amount)
{
this.name = name;
this.amount = amount;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Double getAmount()
{
return amount;
}
public void setAmount(Double amount)
{
this.amount = amount;
}
}
public static void main(String args[])
{
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String name = null;
List<BankAccount> bankAccounts = new ArrayList<BankAccount>();
do
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Please enter the name to whom the account belongs.(\"Exit\" to abort)");
name = kbReader.nextLine();
if (!"EXIT".equalsIgnoreCase(name))
{
System.out.print("Please enter the amount of the deposit. ");
double amount = kbReader.nextDouble();
System.out.println(" ");
bankAccounts.add(new BankAccount(name, amount));
}
}
while (!"EXIT".equalsIgnoreCase(name));
BankAccount maxBankAccount = null;
for (BankAccount bankAccount : bankAccounts)
{
if (maxBankAccount == null)
{
maxBankAccount = bankAccount;
}
else if(bankAccount.getAmount() > maxBankAccount.getAmount())
{
maxBankAccount = bankAccount;
}
}
System.out.println(" ");
System.out.println("The account with the largest balance belongs to " + maxBankAccount.getName() + ".");
System.out.println("The amount that the account contains is $" + formatter.format(maxBankAccount.getAmount()) + ".");
}
}

Related

How do I populate a String array using a for loop [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 4 years ago.
Please bear in mind that I am a beginner.
I have written the following code to try to populate a String array. It runs but will not print out the contents of the String array positions. (The same thing seems to work no problem for the double Array!)I do not understand why this is. If anyone could help me solve this problem I would be extremely grateful. See below for the code of the Main Class and a class called Fruit which contains the methods I am using.
`enter code here`Main class:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Fruit fruit = new Fruit();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of items in your shopping list:");
int listSize = scanner.nextInt();
String[] sl = new String[listSize];
double[] price = new double[listSize];
//Loop asking user to enter items and prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println("Enter item " + (i+1) + ":");
fruit.setName(scanner.nextLine());
sl[i] = fruit.getName();
scanner.next();
System.out.print("Price of " + sl[i] + ":");
fruit.setPrice(scanner.nextDouble());
price[i] = fruit.getPrice();
}
//Loop printing items and their prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println(sl[i] + " cost " + price[i]);
}
//Order the array in ascending order so as to be able to easily
identify the most and least expensive
Arrays.sort(price);
//Print out the most expensive and cheapest prices
System.out.println("The most expensive item costs: " +
price[price.length-1]);
System.out.println("The least expensive item costs: " + price[0]);
}
}
Fruit Class:
public class Fruit {
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
The problem is that the Scanner.readInt() and Scanner.readDouble() methods do not read the newline character after you press enter. However, the readLine() method reads the input that is skipped, so it reads the newline character. To fix the problem, you need to call scanner.readLine() after you call scanner.readInt() and scanner.readDouble() to get rid of the newline. Please see the code below.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Fruit fruit = new Fruit();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of items in your shopping list:");
int listSize = scanner.nextInt();
scanner.nextLine(); //calling nextLine() to get rid of the newline character
String[] sl = new String[listSize];
double[] price = new double[listSize];
//Loop asking user to enter items and prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println("Enter item " + (i+1) + ":");
fruit.setName(scanner.nextLine());
sl[i] = fruit.getName();
System.out.print("Price of " + sl[i] + ":");
fruit.setPrice(scanner.nextDouble());
scanner.nextLine(); //calling nextLine() to get rid of the newline character
price[i] = fruit.getPrice();
}
//Loop printing items and their prices
for(int i = 0; i <= listSize - 1; i++)
{
System.out.println(sl[i] + " cost " + price[i]);
}
//Order the array in ascending order so as to be able to easily
Arrays.sort(price);
//Print out the most expensive and cheapest prices
System.out.println("The most expensive item costs: " + price[price.length-1]);
System.out.println("The least expensive item costs: " + price[0]);
}
}
class Fruit
{
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
I have compiled and run this code, and here is the output it produces:
Enter the number of items in your shopping list:2
Enter item 1:
apple
Price of apple:1.25
Enter item 2:
bread
Price of bread:3.45
apple cost 1.25
bread cost 3.45
The most expensive item costs: 3.45
The least expensive item costs: 1.25
Hope this helps!!

Create an array list in java and store values tied to an employee name

I have a program that calculates an employees annual salary based upon there base salary and commission sales. I want to take the program a step further and create an arrayList that will ask for the employee name and then create an array, store the values from the program and print out those values for each employee name inputted.
I imagine that I need to create a for or a else loop to collect the data. Problem is I'm not sure where to do that and how to create the array. I have two classes:
1 class for my commission variable's and calculations:
package Commissions;
public class Calculations {
double totalSales;
private double comRate = 0.025;
private double annualSal = 80000;
private double salesTarget = 120000;
private double acceleration = 0.015;
private double compensation;
public Calculations (double TotalSales) {
this.totalSales = totalSales;
}
public double getCommissionCalc () {
if (totalSales >= salesTarget) {
compensation = (annualSal + (totalSales * (comRate + acceleration)));
return compensation;
} else if (totalSales >= salesTarget * .8) {
compensation = (annualSal + (totalSales * comRate));
return compensation;
} else {
compensation = annualSal;
return compensation;
}
}
}
1 class for my main and user input
package Commissions;
import java.text.NumberFormat;
import java.util.*;
public class paycheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter the employee name: ");
long empName = input.nextLong();
mediaArray[empName];
System.out.println("Enter your total sales for the year: ");
double totalSales = input.nextDouble();
System.out.println("\r");
Calculations c = new Calculations (totalSales);
System.out.println("Your Total compensation with your annual sales is: " + nf.format(c.getCommissionCalc()));
System.out.println("\r");
System.out.println("If you were to increase your sales you could earn even more money!");
System.out.println("\r");
double i = totalSales + 5000;
double finish = totalSales * 1.5;
while (i <= finish) {
c.totalSales = i;
System.out.println("If you were to increase your sales commission to " + nf.format(i) + " you could earn: " + nf.format(c.getCommissionCalc()));
i = i + 5000;
}
}
}
Here is the code as per my understanding of your problem, had to correct few things as you are saying enter name but taking long as input:
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Paycheck {
public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
while (true) {
Scanner input = new Scanner(System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("Enter the employee name (enter exit to exit): ");
String empName = input.nextLine();
// mediaArray[empName];
if(empName.equals("exit")) {
break;
}
System.out.println("Enter your total sales for the year: ");
double totalSales = input.nextDouble();
Calculations c = new Calculations(totalSales);
System.out
.println("Your Total compensation with your annual sales is: "
+ nf.format(c.getCommissionCalc()));
System.out.println("\r");
System.out
.println("If you were to increase your sales you could earn even more money!");
System.out.println("\r");
double i = totalSales + 5000;
double finish = totalSales * 1.5;
while (i <= finish) {
c.totalSales = i;
System.out
.println("If you were to increase your sales commission to "
+ nf.format(i)
+ " you could earn: "
+ nf.format(c.getCommissionCalc()));
i = i + 5000;
}
System.out.println("\r");
//store employee data into arraylist
empList.add(new Employee(empName, i));
}
for(Employee emp : empList) {
System.out.println("Employee Name: " + emp.getName() + " Total Sales: " + emp.getSales());
}
}
}
class Employee {
private String name;
private Double sales;
public Employee(String empName, double totalSales) {
this.name = empName;
this.sales = totalSales;
}
public Double getSales() {
return sales;
}
public void setSales(Double sales) {
this.sales = sales;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Calling methods of an object that is already stored in an ArrayList

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.

Finding the max value in an arraylist

In this program I wrote I have to print out the name of the customer who spent the most in the store. I need help searching the array list for the customer who spent the most.
package bestcustomer;
import java.util.*;
/**
*
* #author muf15
*/
public class BestCustomer {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Double> sales = new ArrayList<Double>();
ArrayList<String> names = new ArrayList<String>();
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
sales.add(salesAmount);
System.out.println("Enter customers name");
names.add(in.next());
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer(sales, names);
}
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales;
return name;
}
}
You should wrap these two field in a class called probably Customer and then
Use Collections.max();
Collections.max(yourCollection, customComparator);
You should consider making Customer a class, but this would find the name with your current data structures:
public static String nameOfBestCustomer(ArrayList<Double> sales,
ArrayList<String> customers)
{
String name = "";
double maxSales = 0;
int index = -1;
for(int i = 0; i < sales.size(); i++) {
if(sales.get(i) > maxSales) {
index = i;
maxSales = sales.get(i);
}
}
if(index == -1) {
return null; //lists are empty
}
return customers.get(index);
}
I might be a bit late..
I think that if you create a Customer class with two fields, name and sale it would be better design as mentioned by other answers.
Then in BestCustomer you could loop through the list of customer, find the highest sales and return the name.
Something like this for BestCustomer
private ArrayList<Customer> customers = new ArrayList<Customer>();
public BestCustomer(){
Scanner in = new Scanner(System.in);
double salesAmount;
System.out.println("Enter the sales for first customer: ");
salesAmount = in.nextDouble();
while(salesAmount !=0)
{
System.out.println("Enter customers name");
String name = in.next();
customers.add(new Customer(name, salesAmount));
System.out.println("Enter the next sales amount, 0 to exit: ");
salesAmount = in.nextDouble();
}
String bestCustomer = nameOfBestCustomer();
System.out.print(bestCustomer);
}
private double highestSale(){
double highestSale = 0;
for(Customer c: customers)
if (c.getSales() > highestSale)
highestSale = c.getSales();
return highestSale;
}
public String nameOfBestCustomer(){
for (Customer c: customers)
if(c.matchSale(highestSale()))
return c.getName();
return null;
}
}
and this is the Customer
public class Customer {
private String name;
private double sales;
public Customer(String name, double salesAmount) {
this.name = name;
sales = salesAmount;
}
public boolean matchSale(double sales){
return this.sales == sales;
}
public double getSales(){
return sales;
}
public String getName(){
return name;
}
}
I am a beginner so I am pretty sure there is a more efficient way to do it. Also I am using two getters and as far as my understanding goes it is not the better design..
In Java8, if defined Customer like mikey said
customers.stream()
.max(Comparator.comparing(Customer::getSales))
.get()
.getName()

Java assignment don't know what is the mistake

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

Categories

Resources