Searching ArrayList Of Objects
Mar 23, 2014
Okay, I will be as succinct as possible. I am writing a rudimentary book store program for homework. The program consists of two class files and a main. The main issue I am having is on getting the search portion of my program to work. I will post as little as I can and still make sense. This is the block of code belongs to my public Book getBook() method, which is of the BookStore class.
View Replies
ADVERTISEMENT
Jul 23, 2014
'm working on a program that is to act as an inventory for a book store. There are two classes (Store and Book), and numerous methods which you will see in my code. The program is supposed to read in an inventory from a file which contains 10 books (each row in the file represents a book with an ISBN number, the price of the book, and the number in stock)and store this file into an array of type Book[]. There is then to be another method to process a purchase interactively. The Store class is also to keep a count of how many books were sold at the time of closing and also how much was made that day.
I'm having some difficulty figuring out how I should set up the purchase processing method though. I've written out how I think it would be set up (not too familiar with the terminology, but I think it would be called pseudo code?) I'll include that now along with a few other notes.
public Book[] purchase(String isbn, double price, int copies) {
int itemsSold;
double totalMade;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the ISBN number of the book you would like to purchase: ");
[Code] ....
So basically here's what needs to be accomplished with this portion of code:
1.Ask the user to enter the ISBN number of the book they'd like to purchase.
2.Search the array for the object that contains that ISBN.
3.If the ISBN isn't found in the array, display a message stating that we don't have that book.
4.If the ISBN is found but the number of copies is 0, display a message saying the book is out of stock.
5.If the ISBN is found and the number of copies is greater than 0, ask the user how many copies they'd like to purchase.
6.If the number they enter is greater than the number of copies of that book in the array, display a message stating that and ask them to enter another quantity.
7.Once the purchase is complete I need to update the array by subtracting the number of copies of that particular book that was purchased.
8.Print the updated array.
9.Display a count of how many books were purchased, and how much money was made from the purchase.
I know that code has a lot of holes in it, but I'm just trying to get everything together and figure out how to do each step.
The part I'm stuck on right now is trying to figure out how to search the array to first see if the ISBN that was entered is in the array, and then to find the number of copies of the book with that ISBN number.
In case it will visualize what this array looks like, here's a print out of the array from a sample run I just did.
ISBN: 1234567, Price: 31.670000, Copies: 0
ISBN: 1234444, Price: 98.500000, Copies: 4
ISBN: 1235555, Price: 27.890000, Copies: 2
ISBN: 1235566, Price: 102.390000, Copies: 6
[Code] ....
View Replies
View Related
Oct 7, 2014
I'm almost finished my Bank Account exercise and I found myself stuck at the last part. Its asking me to add a method that asks the user to input the name of the account into which they want to deposit money, then search the ArrayList for that account. If it is found, the user is asked how much money they wish to deposit.
I already have my deposit method sorted so basically what I need is just searching through the ArrayList by the name variable. I assume its don't by iterating through with some form of for loop.Heres what I have:
import java.util.Scanner;
public class BankAccount {
private double balance;
private String name;
public BankAccount(double balance, String name){
this.balance = balance;
[Code]......
And the driver class
import java.util.ArrayList;
import java.util.Scanner;
public class BankDriver {
Scanner scan = new Scanner(System.in);
ArrayList<BankAccount> list;
public BankDriver(){
[Code]...
View Replies
View Related
Mar 30, 2014
This is the code fragment I have for searching my ArrayList. Now, each contact is stored in the ArrayList with five elements (first name, last name, etc.) and they're Strings. The error I get when I try to compile my program lies within this code fragment. It says it cannot find the symbol for the search method. I'm not quite sure what to do with this error.
int foundIndex = SAAddressBook.search(aBook);
System.out.println();
if (foundIndex > -1)
aBook.get(foundIndex).displayContact();
else {
System.out.println("No Entry Found");
}
View Replies
View Related
Mar 15, 2015
I have a ArrayList of objects of class called HockeyPlayer (ArrayList<HockeyPlayer>). A HockeyPlayer has a String name and int number of goals.
This is my current work for comparing each object in the list to every other and printing them to screen:
Iterator<HockeyPlayer> it = hockeyPlayersList.iterator();
while (it.hasNext()) {
HockeyPlayer singleHockeyPlayer = it.next(); //the first one encountered
// HockeyPlayer nextHockeyPlayer = it.next(); //the next one encountered
[Code]...
This of course produces some duplication in the print-out: These are the equal hockey players: Who Ever wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
Jason Harrison wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
These are the equal hockey players: Jason Harrison wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
Who Ever wears jersey. This type of employee is paid: true. This employee has post-secondary education: false. This employee's work is to play. This hockey player has scored 0 goals.
How do I remove the duplication in the print-out?
View Replies
View Related
Feb 11, 2014
I am trying to access an array of "Movie" objects in my jsp. The array is loaded via
org.springframework.web.servlet.ModelAndView.addObject().
Here is my jsp code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
[Code] .....
The System.out.println("jsp page: .... &> results in the output: "jsp page: movielist - [Title: Die Hard; Budget: 20000000, Title: two days in paris; Budget: 1000000]" so I am confident the objects are being loaded into the ModelAndView correctly. However the output of the block is "${movie.name}" instead of the list of movies. My movie object has a getName() method to return a string (and a setName() method). I am not sure why the System.out.println statement can find the movielist attribute, but ${movie.name} is being treated a plain text. There are no execptions thrown or other indications of errors.
View Replies
View Related
Jun 20, 2014
I want to clone some Arraylist, but the compiler apparently are just referencing the values to it's original ArrayList. I don't know what should it be:
package projetoteste;
import java.util.ArrayList;
import java.util.List;
public class TestFood {
public static void main(String[] args) {
List food=new ArrayList();
[code]....
Notice that ArrayList dailyMeal should be untouchable, but it return the changes that I made in local for-loop iteration although I didn't added nothing to it, just to it's clone.
Output:
[[[Suco, 1 , 2], [Suco, 1 , 2]], [[Suco, 1 , 2], [Suco, 1 , 2]]]
[[[►, ►, Suco, 1 , 2], [►, ►, Suco, 1 , 2]], [[►, ►, Suco, 1 , 2], [►, ►, Suco, 1 , 2]]]
View Replies
View Related
Nov 15, 2014
So I am working on an assignment and ran into an annoying bug. Basically i have a menu that accesses an ArrayList of Videos which may or may not be read from a file, one of the options of the menu is to edit an existing Video. For this I ask the user for the number of the video and it is checked against the list of video numbers if it returns a match, the method gets the index of the Video object and stores it in a temporary variable the user is allowed to edit the details and the object is put back into the ArrayList using the variable and the ArrayList's set() method
My problem is that once i finish editing the details of a video it gives me a indexOutOfBounds exception
On further investigation using a method that goes through the index of every object in the ArrayList using indexOf() i found out that every single object has been given the index of -1 and not 0,1,2,3 etc.. This is my first error and have not expierenced any other before.
The objects do exist because I have read them from a file. I can also add new Objects and view them successfully but they still have the same index . I have checked my syntax and everything and no errors, this happens at run time only.
I have even created some other ArrayLists seperately and debugged them and their index order is fine. I am too far into this project to start over. I've also tried cleaning the project(my IDE is Eclipse).
View Replies
View Related
Oct 17, 2014
I've two classes: Student and ArrayListExamples (which has my main method in it).
The student class acts pretty simply at the moment with a constructor that takes a name, surname and ID number. I've tested it and it seems to be working. My issue is with adding an object to an array list, here is my effort:
public class ArrayListExamples {
private static int MAX_SIZE = 50;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList();
[code]....
I know the last loop to add the student objects is wrong.I'm calling the student ArrayList add method with a student object whose constructor requires two strings and an integer. Why isn't this allowed?
View Replies
View Related
Jan 23, 2014
I'm having trouble getting new objects to add to an ArrayList. Instead, every time a new object is created and added, it overwrites the first object. So if I read in four lines from a text file and make them into four objects, each overwrites the previous and only the last object is printed. I can print out the contents correctly if I move the println statement within the if-loop; however, I need all the objects to saved to the list for searching (later implementation). i believe it has something to do with the instances of the object, but I'm a little confused about how to fix it. Here's the portion of the code I'm looking at:
Java Code:
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
Scanner scanner = new Scanner(new FileReader(file));
String currentLine;
System.out.printf("%-20s %-20s %-20s
[Code] .....
View Replies
View Related
Feb 25, 2014
How would you display an ArrayList of Objects in a JSP page from a Servlet. Any general example would be fine as long as the example is thorough.
Each created object has more than maybe 6 or 7 properties that all need to print to the JSP.
Would you also include ways of printing it like should it be printed by using a table structure in the JSP and if so how? Things of that nature so that way it is each object has its own line and looks good. I can format it myself, I just need to know how to get it in a table for each object to print on its own row and so on...
View Replies
View Related
Jan 9, 2014
I have a problem with my program. My aim is to display in a JPanel, 2 rectangles, and resize them by clicking. I want to give the user the ability to change the height of the rectangles (independently) by moving the top and/or bottom edges. Currently, it displays the 2 rectangles, but impossible to resize and I can not find the solution.
Java Code:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.*;
public class Resizing extends JPanel {
private static final int PREF_W = 600;
[Code]...
View Replies
View Related
Jan 10, 2014
I have a problem with my program. My aim is to display in a JPanel, 2 rectangles from an arraylist, and resize them by clicking. I want to give the user the ability to change the height of the rectangles (independently) by moving the top and/or bottom edges. There is errors in my code but where ? Netbeans underlines 2 lines (in bold).
My code:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Path2D;
[Code]....
View Replies
View Related
Jun 14, 2014
I've come across something that i'm not overall sure about regarding the static keyword in Java.I'm making a vertical scrolling game where the player simply shoots enemies and they shoot back as they fall, dropping items if they die such as power ups and coins. I have an enemy called Bat and this is the bullet creation code in the update method:
if(oldPlayerY + 220 > posY && getBulletDelay > 0.90f){
batBullets.add(new Bullet(posX + 10, posY - 10));
getBulletDelay = 0;
}
The method is creating a new bullet object and it then adds that to the arraylist called batBullets, which is simple enough. I then need to access this arraylist in the main game update class so I can render those bullets on the screen, even if the bat dies. I was always taught that you use the static keyword when you need to access something from the class that doesn't require an object. Because of this, I have the following code.
for(Bullet bullet : Bat.batBullets){
bullet.setY(bullet.getY - 5); // Set the bullet to fall
renderMap.getSpriteBatch().draw(bullet.batBullet(), bullet.getX(), bullet.getY()); // render the bullets
}
This seems perfectly fine to me because I need to access the batBullet arraylist and it doesn't make sense to create a new bat object as I already have random spawning in place for them.
View Replies
View Related
Oct 14, 2014
I have a requirement to find the greatest/maximum of the given list of Calendar objects in Java.
i.e., 2013/01/26
2014/03/03
2012/02/27
2014/01/15
So the above list of calendar objects are in Arraylist. I need to get the max/greatest among these. Eventually, the answer should be 2014/03/03
View Replies
View Related
Mar 18, 2014
I have to create a method with the following header :
public static <E extends Comparable<E> > void sort ( ArrayList<E> list , int left, int right)
i also had to create a swap cells method and position of max integer method. and also had to read the preserved data file in with a scanner. I implemented the comparable interface I am having difficulty sorting my list by the area. It has to be in descending order.
Geometric Object class: since it has comparator also am interested if i need to change this?
CODE:
Driver:
public static void main(String[] args) throws IOException, ClassNotFoundException {
Circle c1 = new Circle (4, "red", false);
Circle c2 = new Circle (2, "blue", true);
Circle c3 = new Circle (10, "blue", true);
Rectangle r1 = new Rectangle (10, 6, "yellow", true);
Rectangle r2 = new Rectangle ( 5, 11, "green", true);
ArrayList <GeometricObject> list = new ArrayList();
[Code] ....
View Replies
View Related
Nov 4, 2014
I am trying to create a method for my "ticketmachine" object that counts ticket objects in an arraylist of "ticket" objects with a specified field "route". The method works if i change the field type of the ticket class to public, however according to the homework task "route" of the ticket class needs to remain a private field.
Here is my code for the method.
public int countTickets(String route) //HAD TO CHANGE Ticket class FIELD "ROUTE" TO PUBLIC!!!!
{
int index = 0; //returns the number of Ticket objects in the machine with the specified "route".
int ticketCounter = 0;
while (index < tickets.size())
[Code] ....
Is my general approach to the problem wrong? also is there a way to access a private field?
View Replies
View Related
Jan 13, 2014
I have a code to resize a single rectangle. I would like to display and resize multiple rectangles independently and according to my research on the net, the best way is to use an arraylist. So I modified the code in this sense, except ...when I run the code, the rectangles appear good but impossible to resize. I think the problem comes from mousePressed, Released, Dragged and Moved methods. When I use the mouse to resize the rectangle, nothing happens. The code does not interact with the arraylist, and therefore with rectangles it "contains". Resizing is my main class, the MouseAdapter is in the Resizer class (below).
Resizing component; boolean dragging = false; // Give user some leeway for selections.
final int PROX_DIST = 3; Path2D.Double selectedPath; public Resizer(Resizing rz) {
component = rz; component.addMouseListener(this);
component.addMouseMotionListener(this);
[Code] .....
View Replies
View Related
May 11, 2012
I'm doubted regarding the implementation of Collections.binarySearch() method on an ArrayList of objects of a custom class Movie.
Here is the movie class :
public class Movie implements Comparable<Movie> {
String movieName;
String rating;
String director;
String theme;
[Code] .....
The sort/binarySearch in searchByMovieName function is done with natural sorting (and Comparable Interface in Movie class). I mean no comparators involved here. And the comparator that I used for sorting/binarySearching on Movies Director attribute in searchByMovieDirector function is :
public class MovieDirectorComparator implements Comparator<Movie> {
public int compare(Movie movie1, Movie movie2) {
return movie1.getDirector().compareToIgnoreCase(movie2.getDirector());
}
}
But I was not able to implement binarySearch ?? How to implement the binarySearch here. I have google to see only binarySearch working on Arrays or probably ArrayList of String only, but not on ArrayList of custom objects.
View Replies
View Related
Jan 29, 2014
If you were given a problem to search for an error in a section of code but it is incredibly long, what are some ways you can go through the lines of code quickly?
View Replies
View Related
Jan 2, 2015
I have a code that is meant to read a file and organize all the names from least to greatest salaries. It also allows the user to enter a name to find from the file, and the program finds the name and displays it. I have two errors, and I will show the error in my code
View Replies
View Related
Nov 3, 2014
I'm doing LinkedList at the moment and I'm having a bit of trouble with my assignment. The part I'm struggling with is remove an employee from a training course (as specified by their employee number),
what I'm confused about is iterating through the linked list to find the employee we're looking for. What I would do in this situation if I was using an array list is
for(Employee emp : myList) {
if(emp.getEmployeeNumber().equals(searchedNumber)) {
remove from training course..
break;
}
}
"Can only iterate over an array or an instance of java.lang.Iterable" is what it is telling me, and I can't figure out why/how its done differently for linked lists.
View Replies
View Related
Mar 25, 2015
I'm very new to Java, and I'm writing a code to search a string to see how many times the word "dog" is found in it. I'm not sure if this is error-free or the most efficient, but I'd like to keep it simple.
public void run()
{
String input = new String("The Dogman was no ordinary dog, nor man, but rather a peculiar dog-like man who barked like a dog, and panted like a dog, he even ate like a dog. He owned a dog named Doglips, and interestingly enough, his favorite food was hotdogs.");
println(input);
int index = -1;
int count = 0;
print("Counting dogs:");
inputarray = input.split(" ");
[Code] .....
View Replies
View Related
Jun 28, 2014
import java.io.*;
public class pho
{
public static void main (String args[]) throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String name = new String [50];
long phn = new long [50];
System.out.println("enter A for adding phone numbers");
[Code] .....
View Replies
View Related
Nov 2, 2014
My code is not working properly. The ascending and descending numbers are not showing up. I believe what it is printing is the memory location. In this lab you will be coding a program that will make use of functions to search and sort an array. There will also be a print method, again complete with a full menu system. The Menu options are listed below in the section labeled menu.You will need to set up a hundred (100) position integer (int) array that is defined in main. You will also need an integer (int) variable called size. By doing this, you will have to pass the array and the size to each method you write.
Menu:
The menu should have the following eight options:
1. Fill the array with random numbers (1 -100)
2. Print the array
3. Sort the array in ascending sequence
4. Sort the array in descending sequence
5. Sequential search of the array for a
6. Binary search of the array for a target
7. Exit (this can be option zero if you prefer)
From these seven Options, one can see that six methods will be needed. Each of the six main functionalities above will need a function that does what they say. When printing the array, it is required to print the position number alongside the value. Please start your positions at zero, and not one. When doing the sorting methods, please use two different sorting algorithms. (ie, use a Min Max sort for ascending and an enhanced bubble for descending.)
For the Searching methods: you should ask for the target (number the user is searching for) in the dispatch method. Then pass the target to the search method. The search method should return the position it was found at (0 - Size) OR -1 if it was not found. Then have the appropriate messages print inside of the dispatch method.You could write another function that does this part if you wish to keep your dispatch method cleaner and more organized. But that is up to you.
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class Lab9 {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int [] values = new int [100];
[code]....
View Replies
View Related
Apr 30, 2014
Ok here I have a code that generates 1 million random values then converts them to a string then hashcode. I then insert into a linked list and then I want to run through each hash and find it in the linked list timing each run then averaging out the time at the end.
It works great for smaller amounts of numbers it is searching for (fine under 50 thousand searches for the for loop starting at line 24 LinkedListTest.java) but when I try to do the full million searches it gives me "a Exception in thread "main" java.lang.StackOverflowError" at line 158 in List.java. Maybe im getting tired but I cannot figure out why.
// class to represent one node in a list
class ListNode< T >
{
// package access members; List can access these directly
T data; // data for this node
ListNode< T > nextNode; // reference to the next node in the list
[code]....
View Replies
View Related