Linear search array - java

Im working on a project in which it reads book titles in from a .txt file and puts them into an arraylist, then the arraylist is converted to an array, The user enters a number which is the books reference number, then it does a linear search to find that book. Im just having a little trouble with the code for my linear search, heres what I have:
private void FindItActionPerformed(java.awt.event.ActionEvent evt) {
String input;
int int1;
input = Input.getText();
int1 = Integer.parseInt(input);
for(int i=0; i<bookList.length; i++){
if (bookList[i].equals(int1)){
Output1.setText("The Book is " + bookList[i]);
}
}
}
It says .equals() on incompatible types, not sure how to fix, thanks for any help you may be able to offer
public class Book{
String referenceNumber, title;
public Book(String _referenceNumber, String _title){
referenceNumber = _referenceNumber;
title = _title;
}
}
ArrayList <Book> Books = new ArrayList <Book> ();
Book [] bookList;
Here is the Book class and arrays

bookList[i].referenceNumber.equals(input)
This should solve your compatibility problem
On side note, not a good idea to make your class members public..try using getters and setters to change the members..

A little more details: as GoldRoger correctly pointed out, you need to access the referenceNumber of your book. It says incompatible types because you are comparing apples against carrots, or better said Numbers against Books. Accessing the referenceNumber of the book through:
bookList[i].referenceNumber.equals(input)
is the correct approach.

Related

Sorting a linked list using insert sort method in Java

I have an assignment for my class to sort a LinkedList that we made previously using the insert sort method. We created the List by reading in an excel file with 5 contributors listed. I realize this sounds like a repeat question...however, all of the samples I can find deal with Integers or arrays, nothing that I can find deals with strings or with a LinkedList like the one I am using. The other problem, the examples I do find that deal with more than just integers assume you made the list "from scratch", using Head and Node and stuff like that...as you can see in my code, I did not make mine from scratch, I just used the build in Java utility to make mine. Anyways, my code may not be super efficient, but I got a 100 on every assignment so far, so it's good enough for the school I guess, but any suggestions to make it better are welcome as well. I am a beginner to programming, only experience I have is previous classes. So, here is my code:
import java.io.*;
import java.util.*;
public class ChrisJohnson_Unit3_IP {
static class Contributor{ //create class to store contributor information
//declare variables
private String firstName;
private String lastName;
private String country;
private String phone;
private double contribution;
private int id;
//methods for setting variable values
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getCountry(){
return country;
}
public void setCountry(String country){
this.country = country;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone){
this.phone = phone;
}
public double getContribution(){
return contribution;
}
public void setContribution(double contribution){
this.contribution = contribution;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public void Print(){//method to print class objects
System.out.printf("%-10s %-10s %-8s %-15s %s %-15s %d %n", firstName, lastName, country,
phone, "$", contribution, id);
}
}//end Contributor class
static LinkedList contributorList = new LinkedList(); //create new Contributor Linked List
static Hashtable<String, Contributor> memberID = new Hashtable<>();//create new Hash Table
public static void main(String[] arg) throws Exception {
String response;
String ID;
Contributor contributorData = null;
Scanner in = new Scanner(System.in);
//print Welcome message and describe program to user
System.out.println("Welcome! This program will read your contributors.csv file "
+ "and store it into a list. \nTThe program will then sort the list and"
+ "print it for you to view/n");
System.out.println("Press enter to read the currently saved contributors.csv file...");
in.nextLine();
BufferedReader File =
new BufferedReader(new FileReader("contributors.csv"));
String dataRow = File.readLine(); // Read first line.
// The while checks to see if the data is null. If
// it is, end of file has been reached. If not,
// data will be processed.
while (dataRow != null){//While to read contributors.csv file and store in Contributor object
String[] data = dataRow.split(",");
contributorData = new Contributor(); //create new Contributor object
//store data into Contributor object
contributorData.setFirstName(data[0]);
contributorData.setLastName(data[1]);
contributorData.setCountry(data[2]);
contributorData.setPhone(data[3]);
contributorData.setContribution(Double.parseDouble(data[4]));
contributorData.setId(Integer.parseInt(data[5]));
ID = Integer.toString(contributorData.getId());
contributorList.push(contributorData);//add object to top of contributorList
memberID.put(ID,contributorData);//add contributor ID to key element of Hash Table
dataRow = File.readLine(); // Read next line of data.
}//end While to read contributors.csv file
File.close();//close CSV file
System.out.println("Here is your unsorted contributor list:\n");
//call Print method to print the list
System.out.printf("%-10s %-10s %-8s %-15s %-17s %s %n", "First", "Last",
"Country", "Phone #", "Contribution", "ID");
Iterator<Contributor> iter = contributorList.iterator();
while(iter.hasNext()){
iter.next().Print();
}//end while
System.out.println("Thank you for using this program!");
} //main()
}//end ChrisJohnson_Unit3_IP class
Again, the List has to be sorted by Name using the insert sort method. I understand the basic concept of the sort method, but honestly have no clue how to implement it here. I'm not looking for someone to do my homework for me, just give me a push in the right direction. Any help would be greatly appreciated, if you need anymore information please let me know. This assignment is due Monday, so hopefully someone is able to help me out by then. And yes, I have already written my instructor asking for help, I have been out of town all week so I have been trying to play catchup. Thank you for taking the time to read my question
First of all, I should say that doing an insertion sort on a linked list is totally pointless. Secondly, you could do something like the following, if you add a getName method that concatenates first and last names of the contributor (you can concatanate while sorting, but your code will be messier).
for( int i = 1; i < contributorList.size(); i++)
{
int j = i;
Contributor tmp;
while( j > 0 && contributorList.get(j-1).getName().compareTo( contributorList.get(j).getName()) > 0)
{
tmp = contributorList.remove( j);
contributorList.add( j-1, tmp);
j = j - 1;
}
}
First change your contributorList to use the Generic type of the objects it holds. That is LinkedList<Contributor>;. Second change the Object to implement Comparable. That is class Contributor implements Comparable<Contributor> and implement method public int compareTo(Contributor other). Third, pick a sorting method and implement it using compareTo to compare the objects for sorting.
Use ListIterator to find the correct point to insert the element and to the insertion. This allows you to do the insertion sort more efficiently than with the "standard approach", which would run in O(n³), since get and set runs in O(i) for index i. (The inner loop would run in O(i²), since O(1+2+...+i) = O(i²) and O(1²+2²+...+n²) = O(n³)).
Note that using a Iterator is enough to find the insertion point in O(n) and achieve O(n²) running time, but using ListIterator allows you to find and insert the element as well as remove the element for the next iteration of the outer loop iteration only a single iterator, if used in a clever way.
Using a Comparator to compare objects by a specified criterion also allows you to specify a criterion to sort by:
return value of comparator.compare(a, b) | meaning
-----------------------------------------------------------
0 | a == b
> 0 | a > b
< 0 | a < b
In java 8 you can easily create a Comparator given the method reference to a method returning the sort criterion given a object:
Comparator<Contributor> comparator = Comparator.comparing(Contributor::getLastName);
Without using method references this can be done using compareTo of a object implementing the Comparable interface, like String:
Comparator<Contributor> comparator = new Comparator<Contributor>() {
#Override
public int compare(Contributor o1, Contributor o2) {
return o1.getLastName().compareTo(o2.getLastName());
}
};
This way you use the Strategy Pattern for the ordering relation allowing you to use different sortings by passing different Comparators. And it's also the way the Collections class allows you to sort Lists with arbitrary contents, see Collections.sort(List, Comparator).

Easy way to get to values from JSONArray

I recently started working with JSON in Java. We have been setting and getting our values as follows from this JSONArray:
[{"productId":"1"},{"productName":"hammer"}]
JSONObject jo = ja.getJSONObject(0);
We could easily get the values by calling jo.getString("productId"); which would return the 1.
The problem is that sometimes we get different types of JSON objects. They look like this:
[{"name":"productId", "value":"1"},{"name":"productName", "value":"hammer"}]
Is there a way to easily eliminate those predicate name/value and just group the actual name and value together (as in the first example)?
The short answer is no.
The longer answer is that you're not working with JSON, you're working with someone's misunderstanding of JSON.
Both of your examples look a bit like JSON, but they're both bogus.
[] is an array.
{} is an object.
Your first string [{"productId":"1"},{"productName":"hammer"}]
is an array of two objects, where each object has one property.
It's confusing to put dissimilar objects into an array together, but that's going on in both of your examples.
The second example [{"name":"productId", "value":"1"},{"name":"productName", "value":"hammer"}] shows an array of two objects, but again, the objects are dissimilar.
I think what they're going for is more like [{"productId":"1","productName":"hammer"}], so I guess the long answer to your question is that you need to go to whomever is providing this "JSON" and tell them to fix it.
To give you a clearer idea of the correspondence between objects (in Java and otherwise) and JSON, check out the Java program below:
public class Product {
String productName;
String productId;
public Product(String productId,String productName){
this.productName = productName;
this.productId = productId;
}
public String toString(){return toJSONString();}
public String toJSONString(){
return "{\"productId\":\""+productId+",\"productName:\""+productName+"\"}";
}
public static String arrayToJSONString(Product[] arry){
StringBuilder sb = new StringBuilder();
sb.append("["+arry[0]);
for (int n =1;n<arry.length;n++){
sb.append(","+arry[n]);
}
sb.append("]");
return sb.toString();
}
public static void main(String [] args){
Product p1 = new Product("1","hammer");
Product[] arry = {p1};
Product[] arry2 ={p1,new Product("2","shovel"), new Product("3","manure")};
System.out.println("One object");
System.out.println(" "+p1);
System.out.println("An array containing one object");
System.out.println(" "+Product.arrayToJSONString(arry));
System.out.println("An array containing three objects");
System.out.println(" "+Product.arrayToJSONString(arry2));
}
}
Here's the output showing the proper JSON representation:
One object
{"productId":"1,"productName:"hammer"}
An array containing one object
[{"productId":"1,"productName:"hammer"}]
An array containing three objects
[{"productId":"1,"productName:"hammer"},{"productId":"2,"productName:"shovel"},{"productId":"3,"productName:"manure"}]
(Newlines are an artifact of the HTML, not JSON)

create array of NPCs in a game

I am taking a Java class right now and we are supposed to be making a text based game. One of the options in our game is to allow the person to choose between 3 ship types; small, medium, and large. Based on their selection, they will be able to choose how many people travel on the ship. Small allows up to 3, medium up to 6, and large up to 9. Once they have made this selection, they are allowed to enter a name for each crew member and select a research specialization. Previously, we had set these as separate menus (select Ship, crew size, research spec, and names) but I'm beginning to think it would be easier to select crew size, names, and research spec in the same menu.
That said, we are working on arrays/ArrayLists right now and we're supposed to use an array to list the characters (NPCs) in the game. So, I need to figure out how to create an array based on how many crew members are chosen (between 1 and 9), have it then prompt for a name, and then allow them to choose from a list of research specs. They will enter a single letter for their choice but the array should put the full name of the research spec in it. I found some code in another post I think might be helpful in this situation but it's barely scratching the surface I think. Any help would be greatly appreciated.
public class Name {
public static void main(String[] args) {
ArrayList<String> name = new ArrayList<String>();
ArrayList<(how do I tell it to select a character option here?)> researchSpec = new ArrayList<(selected option)>();
Scanner sc = new Scanner(System.in);
while (true) {
System.err.println("Please enter the name of your crew member: ");
name.add(sc.next());
System.out.println("Please select a Science Specialization for your crew member");
researchSpec.add(sc.next());
}
}
}
When you have a small, predefined set of possible values for something, an enum is often ideal for representing those.
public enum Specialization {
PHYSICS,
CHEMISTRY,
BIOLOGY
}
Now, you can define variables of the type Specialization and lists of the type List<Specialization>, and refer to the values as Specialization.PHYSICS etc. This is better than using a String because you're not running the risk of e.g. misspelling a specialization somewhere in the code, such as adding "Pysics" to the list in one place and wondering why the if (specialization.equals("Physics")) never works.
However, you still need to have some ifs, a switch, or a Map for the mapping from letters to specializations - unless you get fancy with the enums. An enum is actually a class, but you can't use new on it - instead, there's automatically one instance per identifier (in this case, PHYSICS, CHEMISTRY, and BIOLOGY are the three only instances). You can add fields, constructors, and methods to an enum class, so that you can endow each value with different properties:
public enum Specialization {
PHYSICS('p', "Physics"),
CHEMISTRY('c', "Chemistry"),
BIOLOGY('b', "Biology");
private char menuLetter;
private String displayName;
private Specialization(char menuLetter, String displayName) {
this.menuLetter = menuLetter;
this.displayName = displayName;
}
public char getMenuLetter() { return menuLetter; }
public String getDisplayName() { return displayName; }
}
You can use values() to get a list of all of the values. For example, this will generate the menu options (I'll leave the selection as an exercise for you):
for (Specialization s : Specialization.values()) {
System.out.println(s.getMenuLetter() + ": " + s.getDisplayName());
}
Edit: Or with a regular loop:
Specialization[] specializations = Specializations.values();
for (int i = 0; i < specializations.length; i++) {
System.out.println(specializations[i].getMenuLetter() + ": " + specializations[i].getDisplayName());
}
Creating an Array based on the selection and then filling it would look like this:
NPC[] npcs;
if (amount > maximum) {// both values prompted
System.our.println("Too much crew members.");
return;
}
npcs = new NPC[amount];
for (int i = 0; i < npcs.length; i++) {
String name = // prompt name
Specialization s = // prompt that somehow -> enum solution by Aasmund Eldhuset
npcs[i] = new NPC(name, s);
}
The NPC class would look like this:
public class NPC {
public (final?) String name;
public (final?) Specialization spc;
public NPC(String name, Specialization s) {
this.name = name;
this.spc = s;
}
}

How to merge an array of objects into a single formatted String

I have been looking for this answer for the past 2 hours with no luck so I am posting my question now. I am sorry if it is similar to one already asked but I could not get an clear answer from what was already answered.
Here goes:
I am doing a school project in which we read in a text file of "Computer" objects (there are 8 fields in total in this form: manufacturer:model:memory:diskMemory:CPU:opticalDrive:OSVersion:RetailPrice)
once the file is read you are supposed to separate the fields and construct an array of Computer objects using the constructor that accepts all the above parameters (separated) and store their reference in each position of the array.
Here is where my question is:
Afterwards you display a menu and the user selects a few option, the simplest is just to display the list of computer object in the following form on a JOPtionPane:
Manufacturer1 model1 memory1 disk1 CPU1 optical1 OS1 retailPrice1
Manufacturer2 model2 memory2 disk2 CPU2 optical2 OS2 retailPrice2
and so on until you finish the array. I cannot figure out how to condense the array of objects into a single string that is in the form above. The Computer class has a getMethod for each of those fields I am just having trouble getting them to be aligned in that way. It has to be on a JOPtionPane the simple .INFORMATION_MESSAGE kind. If you all need to see the Computer class code let me know and I can post it. This is my first time posting on this website so I apologize if it is in improper form.
Thank you so much for your help,
Bob
EDIT:
This is what the output should look like:
http://i229.photobucket.com/albums/ee38/Yukijin-Uchiha/ScreenShot2014-03-14at113759AM_zps05b5dbb5.png
If you implement the Computer classes toString() function properly, you should get just what you want. For example:
public class Computer {
public String toString() {
return (new StringBuilder(getManufacturer()).append(":").
append(getModel()).append(":").
append(getMemory()).append(":").
append(getDiskMemory()).append(":").
append(getCPU()).append(":").
append(getOpticalDrive()).append(":").
append(getOSVersion()).append(":").
append(getRetailPrice()).
toString();
}
}
Then call it with
String computerObjAsString = aComputerInstance.toString();
To do this with an array of Computer objects:
StringBuilder outBldr = new StringBuilder();
for(Computer cmptr : anArrayOfComputers) {
outBldr.append(cmptr).append(System.getPropetry("line.separator", "\r\n"));
}
System.out.println(outBldr);
You should look to override the toString() method in your Computer objects to include the details that you want printed. Then, for each Computer object in your array, call <object name>.toString() to display the appropriate information.
public class Computer {
private String name;
private String type;
public Computer(String n, String t) {
this.name = n;
this.type = t;
}
public String toString() {
return "Name: " + this.name + " Type: " + this.type;
}
public static void main(String[] args) {
Computer c = new Computer("atari","old-school");
System.out.println(c.toString());
}
}

OOP Java: Creating a stock inventory program

I am fairly new to object oriented programming, so I am still having some trouble grasping some of the basic concepts. So here I am trying to create a basic inventory program to keep track of stocks. Each stock contains couple details: company name, stock rating (AAA, AAa, Aaa, stuff like that), purchase price and numbers of shares. The program will ask user to input these details through command line prompt. And users can only input at most 12 stocks. If the user enters a stock twice, it will print out an error. And if the user has inputted one stock twice, it will also print out an error message.
Here is what I have done so far: Stock object
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
public String getCompanyName() {
return companyName;
}
public int getStockRating() {
return stockRating;
}
public String getPrice() {
return price;
}
public int getNumberOfShares() {
return numberOfShares;
}
public Stock(String companyName, String stockRating, int price, int numberOfShares) {
super();
this.companyName = companyName;
this.stockRating = stockRating;
this.price = price;
this.numberOfShares = numberOfShares;
}
Now, I am trying to create stock inventory program
import java.util.*;
public class StockInvetory {
private static final int INVENTORY_SIZE = 12;
private Stock [] stocks;
public StockInvetory() {
stocks = new Stock [INVENTORY_SIZE];
}
private static void StockInventory() {
for (int i = 0; i<INVENTORY_SIZE; i++){
Scanner console = new Scanner(System.in);
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stocks [i]= new Stock(stockName, stockRatings, stockPrice, numberShares);
}
public static void main (String [] args){
StockInventory();
}
}
So my questions are the following:
The first stock object program should be okay, my problem is the stock inventory program.
With this code, private Stock [] stocks, does it mean that the stock inventory program will store the info into an array? If it is, how do I store all the details associated with a particular stock, company name, price, etcs together. Do I have to create a multi-dimensional array in order of keep track of all the details? Like one row contains all the details about one stock, and second row contains details about another stock. And to determine if the user has entered one stock twice, do I use "equalsIgnoreCase" to do the comparison? I know I probably need to create another method for the stock Inventory.
Thank you very much in advance for your assistance.
Once you read in the name, rating, price, and share count, you need to call the constructor on your class Stock to create an instance of the class and assign it to the next item in your stocks[] array.
Like so:
stocks[0] = new Stock( stockName, stockRating, stockPrice, numberShares);
Then you'll need to put the lines of code that you're using to read from the console, plus my line that creates the new Stock object into a loop so that you can read in all 12 stocks:
for( int i = 0; i < INVENTORY_SIZE; i++ )
{
System.out.println ("Stock's name:");
String stockName = console.next();
System.out.println ("Stock's rating");
String stockRating= console.next();
System.out.println ("Stock's price:");
int stockPrice = console.nextInt();
System.out.println ("Numbers of shares: ");
int numberShares= console.nextInt();
stocks[i] = new Stock( stockName, stockRating, stockPrice, numberShares);
}
Now, this isn't perfect, since it will require users to always enter a full set of 12 stocks, so you'll need to figure out how to let the user abort out of the loop if they're done, and you'll still have to add that error checking you want, to ensure that no duplicates are entered, but it should initialize your individual objects and assign eachh one to the array elements.
private Stock [] stocks, does it mean that the stock inventory program
will store the info into an array? If it is, how do I store all the
details associated with a particular stock, company name, price, etcs
together.
Your array is like a list of stocks. But just because its one object, doesn't mean it only contains one piece of data. It can hold Strings, ints, and other user-defined data types. Therefore, you can store pieces of data relating to the stock inside the Stock object.
public class Stock {
private String companyName;
private String stockRating;
private int price;
private int numberOfShares;
Those are all stored in each Stock object, and can be accessed by the getter methods you defined.
int stockdata = stocks[4].getPrice();
However, to initialize your Stock array, you want to create a new Stock object for each area, like so:
for(int i = 0; i < INVENTORY_SIZE; i++) {
stocks[i] = new Stock(foo, bar, lorem, ipsum);
}
The variables used here are just placeholders, so you can create your parameters by reading from the console like you're doing above.
These design principles for OOP should help you understand the relationship between data and containers.
For the second part of your question, you can look at just comparing one of the data values, like companyName, or implementing an interface like Comparable.
for(Stock s : stocks) {
if(stockName.equals(s.getCompanyName()) {
// ERROR!
}
}
You may want to provide some way to break the loop in certain condition if user does not want to input all 12 information. However, it is totally on your requirements.
In that case, you may have to use other options like List or vector.
Each object can have multiple variables , like in your case rating, price ,name and share which are bound to each object. So when you store an object in an index of array, you are actually storing all those information contained by that object in one single place. So in this case, you do not have to create multidimensional array.
You can override your equals method based on what defines the object as equal and use it to determine if same stock is provided again. This will return true if both object are same, otherwise false.
You can post your updated code and log here so that you can get suggestion regarding your exception
In a real world scenario some questions come to mind:
price shouldn't be an integer because a price is usually an amount in a specific currency. Check this money related question.
Stock rating would be better represented using an Enum. See doc

Categories

Resources