I have the following text in a file :
3
apple 4 1.00
chicken 1 3.25
cookie 38 0.25
avocado 1 4.00
blueberries 1 5.00
chicken 2 3.25
milk 9 4.50
tomato 27 0.50
chicken 2 3.25
I want to list each item and its number and its price but I want that if I encounter the same item again to add its number to the existing number I have
I figured out the first part but I can't get the second any one has any ideas ?
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(new File("Groceries.txt"));
while(sc.hasNext()) {
String line=sc.nextLine();
Scanner ss = new Scanner(line);
if(ss.hasNextInt()) {
ss.next();
}
while(ss.hasNext()) {
String name=ss.next();
int number = readInt(ss);
double price = ss.nextDouble();
System.out.printf("The item is %s its number is %d and its price is %.1f\n",name,number,price);
}
}
}
public static int readInt(Scanner sc) {
while(!sc.hasNextInt()) {
sc.hasNext();
}
return sc.nextInt();
}
Create a container object like so:
public class Container
{
private String item;
private double cost;
...
}
Use a HashMap<Container, Double> as your data structure. Every time you come across a duplicate, update its value.
If there is a possibility for an arbitrary amount of repeats, you can use do the following:
public class ValueContainer
{
private int count;
private double value;
}
and have a HashMap<Container, ValueContainer>, and update accordingly. There seems to be some confusion between what you say in the question and in a comment. Regardless, with simple substitutions, this construct will get you to where you want to go.
Create a class describing the attributes of your item (name, price, quantity , count etc).
Create a list of items (Yes, use generics..) // u can also use a map instead of a list..
Now, with each line you read from the text file, first get the item name using split().
Check if the item is already present. If yes, take it out, increment its count and put it back. if No, then add a new item to the list.
Happy Coding...
Related
I'm extremely new to Java, and I'm trying to understand why an output of the main method of the Magic class for this code is "TT". Our professor said we don't have to understand the meaning of this method, but just answer the output.
The code is this.
public class Magic
{
public static void main(String[] args)
{
final String MSG = "Good Restaurant Seattle";
Stock stock = new Stock("HR.S");
double price = stock.getPrice();
int cent = (int) Math.rint(price);
System.out.println(MSG.substring(cent, cent+2).toUpperCase());
}
}
I understand where it took the letters from and how all variables such as cent and price are connected, but I don't understand what "HR.S" is and how it's connected to the output.
In order for MSG.substring(cent, cent+2).toUpperCase() to return TT, the value of cent has to be 20.
....:....1....:....2...
Good Restaurant Seattle
^^
In order for cent to be 20, the value of price must be 19.5 <= price <= 20.5.
Which means that stock.getPrice() returned a value between 19.5 and 20.5 (inclusive).
Not knowing what class Stock does, we cannot say how it figured out that input "HR.S" should have such a price.
I have a a textbook question that I have attempted many times and still does not work here are the instructions:"
Write a Payroll class that uses the following arrays as fields:
employeeId. An array of seven integers to hold employee identification numbers. The array should be initialized with the following numbers:
5658845 4520125 7895122 8777541 8451277 1302850 7580489
hours . An array of seven integers to hold the number of hours worked by each employee
payRate . An array of seven double s to hold each employee’s hourly pay rate
wages . An array of seven double s to hold each employee’s gross wages
The class should relate the data in each array through the subscripts. For example, the number in element 0 of the hours array should be the number of hours worked by the employee whose identification number is stored in element 0 of the employeeId array. That same employee’s pay rate should be stored in element 0 of the payRate array.
In addition to the appropriate accessor and mutator methods, the class should have a method that accepts an employee’s identification number as an argument and returns the gross pay for that employee.
Demonstrate the class in a complete program that displays each employee number and asks the user to enter that employee’s hours and pay rate. It should then display each employee’s identification number and gross wages.
Input Validation: Do not accept negative values for hours or numbers less than 6.00 for pay rate."
so far I have my main class:
public class Payroll {
public static void main(String[] args){
Pay work = new Pay();
Scanner input = new Scanner(System.in);
int[] hours = new hours[work.getLength()];
for (int i=0; i<work.getLength(); ++i) {
System.out.println("How many hours has Employee #"+work.getEmployeeId(i)+" worked?");
input.nextInt() = hours[i];
while (hours[i]<6){
System.out.println("Error, inadequit value!");
System.out.println("How many hours has Employee #"+work.getEmployeeId(i)+" worked?");
input.nextInt() = hours[i];
}
}
}
I also have a class named Pay:
public class Pay {
private int[] employeeId;
//private int[] hours = new hours[employeeId.length];
//private int[] pay = new pay[employeeId.length];
//private int[] wage = new wage[employeeId.length];
public Pay() {
employeeId = new int[]{5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
}
public int getLength(){
return employeeId.length;
}
public int[] getEmployeeId(int id) {
return employeeId[id];
}
I'm just not sur where to go next after all of this. Please help.
I am going to answer this for the simplest way instead of the proper way, since I'm assuming you are somewhat new to programming. This is based on the fact that there seems to be no emphasis on class or any real modularization.
You just want to have 4 arrays of size 7.
The employee ids array will be set by you.
As you prompt the user for the information you save it in the correct array based on the index of the employee being set.
The method for gross pay would just take the id number of the employee, find their index number in the arrays and get the information necessary to calculate and return the gross pay. (presumably gross pay is wageRate * hoursWorked)
This is the simplest way of doing it, separate classes aren't necessary.
A better way of doing this, on object-oriented principles, will be to avoid using multiple arrays. Instead create a class that holds all the employee attributes together, as an object.
public class Employee {
private int id;
private int hours;
private double rate;
// constructors
// it should not have arguments such as id, hours or rate
// because it is a method of this class and those attributes are
// implicitly assumed.
public double getWage() {
return hours * rate;
}
// toString method
#Override
public String toString() {
return "Employee ID = " + id + "," + "hours = " .....
}
}
Wage can be pre-calculated and stored as another field at the time of construction. Or calculated at the time of request as is done above.
The Payroll class:
public class Payroll {
private Employee[] employees;
private int lastIndex = 0;
// constructors
// for example, one constructor can accept initial size
public Payroll(int size) {
employees = new Employee[7];
};
public addEmployee(Employee employee) {
// need to check overflow before attempting to add
// add employee
employees [lastIndex ] = emplyee;
lastIndex++;
}
// more methods, such remove etc
}
Now the driver, or application class
public class Driver {
public static void main(String[] args){
Payroll payroll = new Payroll (7);
// code to pupulate the Payroll with values
for ( ) {
// construct new Emplyee object
// add object to Payroll
}
// Printing
for (Emplyee e: Payroll) {
System.out.println(e.toString());
}
}
}
Note that the application or driver class is separated from the Payroll, now each class does one thing, and only that thing. Remember that it is not the concern of Payroll class to populate itself or print its content etc.
I have to read two sets of integers in a text file. One is the number of credits that a student can have and then the next integer is a letter grade on a test. I can read the integers into an ArrayList, but the issue is that I want to read first the amount of credit they have, then choose which ArrayList to add them to, under a certain amount of credit or over a certain amount. I don't want to add the amount of credits up, just the grade they received. I have 25 lines of integers in the text file, first is the amount of credit, then a space, and then the grade. I only need to record the grade, not the credit amount.
Here is what my code looks like so far:
public static void main(String[] args) throws FileNotFoundException
{
try
{
ArrayList <Integer> over15credits = new ArrayList<>();
ArrayList <Integer> under15credits = new ArrayList<>();
FileReader myReader = new FileReader("geomClass.txt");
Scanner fileIn = new Scanner(myReader);
while(fileIn.hasNextInt())
{
if(fileIn.nextInt() >= 15)
{
over15credits.add(fileIn.nextInt());
}
else
{
under15credits.add(fileIn.nextInt());
}
System.out.println(over15credits);
System.out.println(under15credits);
}
}
catch(FileNotFoundException e)
{
System.out.println("!!FILE NOT FOUND!!");
}
}
When you perform fileIn.nextInt() it reads and consumes the number so that when you call fileIn.nextInt() again it will read the number after that.
Most likely you meant to use a variable so that you can use the number you just read.
int num = fileIn.nextInt();
if (num >= 15)
over15credits.add(num);
else
under15credits.add(num);
You want to use the same number you just read not another number.
FYI you can also write it like this.
int num = fileIn.nextInt();
(num >= 15 ? over15credits : under15credits).add(num);
I have the following code where I'm reading from a text file. The text file i as follows:
111 Laptop 500 10
222 Mobile 120 8
333 Notebook 4 100
444 Chocolates 3 50
555 Guitar 199 5
666 LenovoLaptop 470 10
777 HPLaptop 450 10
888 SonyVAIO 525 5
If the user enters ID as 111, the following should be the output:
111 Laptop 500 10
666 LenovoLaptop 470 10
777 HPLaptop 450 10
888 SonyVAIO 525 5
I'm storing the the contents of the text file in a HashMap. Here is the code:
public void comparableItems(String ID)
{
File f = new File("C://Class/items.txt");
HashMap<String, Item> map = new HashMap<String, Item>();
try
{
Scanner scan = new Scanner(f);
while(scan.hasNext())
{
String line = scan.nextLine();
String temp[] = line.split(" ");
Item it = new Item(temp[0], temp[1], Double.parseDouble(temp[2]), Integer.parseInt(temp[3]));
map.put(it.itemID, it);
}
if(map.containsKey(ID))
{
Item item = map.get(ID);
if(item.price>=item.price+100 && item.price<=item.price-100)
{
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Here is the Item class:
public class Item
{
String itemID;
String itemName;
double price;
int quantity;
public Item(String itemID, String itemName, double price, int quantity)
{
this.itemID = itemID;
this.itemName = itemName;
this.price = price;
this.quantity = quantity;
}
public void printItemDetails()
{
System.out.println("ID\tItemName\tUnitPrice\tQuantity");
System.out.println("===================================================");
System.out.println(this.itemID+ "\t" +this.itemName+ "\t" +this.price+ "\t"+this.quantity);
}
}
How do I get the desired output? I'm in the learning stages of Java Collections. So please bear with me.
Can someone help me here?
Thanks!
Your Map isn't doing you much good. Since you know what reference item ID you're looking for before you even parse the file, you could just capture that item when (and if) you see it during the parse. You do need some kind of collection to hold all the other items, but a List would be a better choice for this particular task.
In any case, the thrust of your question seems to be about examining all the other items you parse from the file. For this, you want to iterate over the Map's values() view (and to get your comparisons right):
for (Item otherItem : map.values()) {
if((otherItem.price <= item.price + 100)
&& (otherItem.price >= item.price - 100)) {
otherItem.printItemDetails();
}
}
If you collected the items in a List instead of a Map, then you would replace map.values() in the above with just list (or whatever name you use for the List).
For what you say you want (items with prices near the desired item), a HashMap isn't an efficient datastore.
However, since it sounds like this is your homework, once you use map.get("111") to get your laptop, get the price P, and then iterate over the hashmap to get any item whose price is within your desired delta of P. The Collections tutorial tells you how to iterate over a collection.
The Prompt:
A program that accepts a candy name (for example, “chocolate-covered blueberries”), price per pound, and number of pounds sold in the average month, and displays the item’s data only if it is a best-selling item. Best-selling items are those that sell more than 2000 pounds per month.
b. A program that accepts candy data continuously until a sentinel value is entered and displays a list of high- priced, best-selling items. Best-selling items are defined in Exercise 2a. High-priced items are those that sell for $10 per pound or more.
Here is an example of a good design in operation:
High-priced, Best-selling Candy
Fudge $12.50 4500 lbs
Vanilla Creme $13.75 2200 lbs.
Fudge, 12.50, 4500 Jawbreakers, 6.50, 5500 Chocolate, 14.00, 790 Butterscotch, 9.50, 4500 Vanilla Creme, 13.75, 2200
Item that sold most pounds: Jawbreakers
but the problem I am having is that my teacher is not letting me use for loops, or arrays. And I do not want to define multiple instances of the same variable because it is finite to a certain amount.... What would be the most efficient way of doing this?
start
// Declarations
num QUIT = "Y";
final String HEADING = "High Priced, Best Selling Candy" + "\n" + "\n";
final String HSPS = candyName + " " + candyPrice + " " + candySold + " ";
final String MOSTSOLD = "Item that sold the most pounds is "
while <> QUIT;
enterCandy();
printHighPriceBestSelling();
printSoldMostPounds();
endwhile;
stop
entercandy()
String candyName = "poop";
double candyPrice = 0.0;
double candyWeight = 0.0;
int candySold = 0;
output "Please enter name of candy.";
input candyName;
output "Please enter candy price.";
input candyPrice;
output "Please enter pounds sold.";
input candySold;
printHighPriceBestSelling()
if(candySold > 2000 && candyPrice > 10)
{
output HEADING;
output HSPS;
}
else
{
output "There were/are no best selling, high priced candy!"
}
printSoldMostPounds();
//There is no basis for comparison.
There are only two ways of doing this. Create lots of different, artbitrary, and predefined variables to be filled by the loop until they are overwritten. Lets say 10. Or create an array. I am sure there is an overly complex way of doing it with nested if/switch/while loops, but why teach us/force us to use the ugly inefficient way?
output "MOSTSOLD ";
I'm assuming that, besides arrays, you're teacher isn't allowing you to use any standard Collection objects.
You could always just build your own LinkedList of entered candy orders--it's ugly, but it would work. A single "link" in the chain would look like this
public class CandyOrderLink {
private String candyName;
private Double candyPrice;
private Double orderAmount;
private CandyOrderLink nextOrderLink;
public CandyOrderLink(String candyName, Double candyPrice, Double orderAmount) {
this.candyName = candyName;
this.candyPrice = candyPrice;
this.orderAmount = orderAmount;
}
public CandyOrderLink getNextLink() {
return nextOrder;
}
public void setNextLink(CandyOrderLink nextOrderLink) {
this.nextOrderLink= nextOrderLink;
}
public String getCandyName() {
return candyName;
}
public Double getCandyPrice() {
return candyPrice;
}
public Double getOrderAmount() {
return orderAmount;
}
}
Not sure if I'm quite grasping the point of the assignment, but using a list data-structure to keep track of all orders will work. Just build a link for each entry (candyName, price, amount) and set that link as the next link of the previous one. At the end of input, iterate through the list by repeatedly calling getNextLink() on each link and printing information (if appropriate). Here is Wikipedia's article on linked lists: http://en.wikipedia.org/wiki/Linked_list
From the problem's description, I see no need to store the data entered so that it can be sorted. Both a and b state simple conditions for displaying a candy: greater than 2,000 pounds and at least $10/lb. You can print each entry immediately after it is entered.
However, your example output implies that you must pick the single best-selling candy which contradicts the description. Which is correct?