i've built a BST that have elements of (country code(string), indicator code(string), indicator name(string) and ArrayList of Years(int) and values(string)).
I'm trying to figure out how to prompt the user to search by entering Indicator code and then the year which the output will be the value.
it would be much appreciated if you could show how to code the search method cause I've tried everything.
I've tried this in the BST class. but it doesn't feel right(?)
public void search(Indicator indicator, String searchTerm){
String str = (String)indicator.getICode();
int n1 = str.compareTo(searchTerm);
int n2 = searchTerm.compareTo(str);
if (str == null || str.equalsIgnoreCase(searchTerm)){
return str;
}
if (n1 > n2){
return search(indicator, searchTerm);
}
else if (n1 < n2){
return search(indicator, searchTerm);
}
}
this is my application class:
public class BigDataBST{
public static void main (String [] Args) throws IOException {
try{
BST bigdata = new BST();
MyData d1;
File inFile = new File ("Indicator.txt");
FileReader fr = new FileReader (inFile);
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
while(str != null ){
StringTokenizer st = new StringTokenizer(str,";");
ArrayList <MyData> data = new ArrayList();
String cCode = st.nextToken();
String iName = st.nextToken();
String iCode = st.nextToken();
for (int j = 0; j < 59; j++){
String v = st.nextToken();
int year = 1960 + j;
d1 = new MyData (year,v);
data.add(d1);
}
Indicator idct = new Indicator (cCode,iName,iCode,data);
bigdata.insertNode(idct);
str = br.readLine();
}
TreeNode class:
TreeNode left;
TreeNode right;
Indicator idct;
public TreeNode(Indicator id){
left = right = null;
idct = id;
}
indicator class:
private String cCode; //country code
private String iName; //indicator Name;
private String iCode; //indicator code;
public ArrayList <MyData> DataList;
public Indicator(){
cCode = null;
iName = null;
iCode = null;
DataList = null;
}
public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
this.cCode = cCode;
this.iName = iName;
this.iCode = iCode;
this.DataList = DataList;
}
//setter & getter method for attributes iCode,iName and cCode
//toString method
MyData class:
private int year;
private String value;
public MyData(){
year = 0;
value = null;
}
public MyData(int year, String value){
this.year = year;
this.value = value;
}
//setter & getter method for attributes year and value
//toString method
example of indicator.txt:
(from left: cCode; iName; iCode; values)
MYS; Employment in industry (% of total employment) (modeled ILO estimate); SL.IND.EMPL.ZS;
29,08600044;28,56900024;28,36300087;28,02300072;27,51600075;27,48699951;27,39800072;27,30500031
I think you don't know how to search in a Binary Search Tree. You can do this by going to each node and can use recursion to do so.
In your search() you are taking Indicator as a parameter, but actually you need to take TreeNode because every node has a data of type Indicator which you can access.
In your search() you are calling the search() again and again with same parameters which will not give you results ever. Moreover, you don't have a base case. That's not how recursion work. You will be getting a stackoverflowException(Hahaa, its funny because we are on StackOverFlow). Use this code instead:
public void search(string key)
{
searchHelper(key, root); // root node will be in Tree.java
}
public void searchHelper(string key, TreeNode current)
{
if(current == null)
{
System.out.println("\nCant find !");
return;
}
if(key.compareTo(current.idct.getICode()) < 0 )
searchHelper(key, current.left);
else if(key.compareTo(current.idct.getICode()) > 0)
searchHelper(key,current.right);
else
System.out.println("\n"+current.idct + "Found \n");
}
Related
I am in a java programming class and I cannot figure how to fix this error.
This is the error I keep getting:
Library.java:120: error: class, interface, or enum expected
import java.util.ArrayList;
^
1 error
This is the task
Two sorted lists have been created, one implemented using a linked list (LinkedListLibrary linkedListLibrary) and the other implemented using the built-in ArrayList class (ArrayListLibrary arrayListLibrary). Each list contains 100 books (title, ISBN number, author), sorted in ascending order by ISBN number.
Complete main() by inserting a new book into each list using the respective LinkedListLibrary and ArrayListLibrary insertSorted() methods and outputting the number of operations the computer must perform to insert the new book. Each insertSorted() returns the number of operations the computer performs.
Ex: If the input is:
The Catcher in the Rye
9787543321724
J.D. Salinger
the output is:
Number of linked list operations: 1
Number of ArrayList operations: 1
This is my code:
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
public class Library {
public static void fillLibraries(LinkedListLibrary linkedListLibrary, ArrayListLibrary arrayListLibrary) throws IOException {
FileInputStream fileByteStream = null; // File input stream
Scanner inFS = null; // Scanner object
int linkedListOperations = 0;
int arrayListOperations = 0;
BookNode currNode;
Book tempBook;
String bookTitle;
String bookAuthor;
long bookISBN;
// Try to open file
fileByteStream = new FileInputStream("Books.txt");
inFS = new Scanner(fileByteStream);
while (inFS.hasNextLine()) {
bookTitle = inFS.nextLine();
bookISBN = inFS.nextLong();
inFS.nextLine();
bookAuthor = inFS.nextLine();
// Insert into linked list
currNode = new BookNode(bookTitle, bookAuthor, bookISBN);
linkedListOperations = linkedListLibrary.insertSorted(currNode, linkedListOperations);
linkedListLibrary.lastNode = currNode;
// Insert into ArrayList
tempBook = new Book(bookTitle, bookAuthor, bookISBN);
arrayListOperations = arrayListLibrary.insertSorted(tempBook, arrayListOperations);
}
fileByteStream.close(); // close() may throw IOException if fails
}
public static void main (String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int linkedListOperations = 0;
int arrayListOperations = 0;
// Create libraries
LinkedListLibrary linkedListLibrary = new LinkedListLibrary();
ArrayListLibrary arrayListLibrary = new ArrayListLibrary();
// Fill libraries with 100 books
fillLibraries(linkedListLibrary, arrayListLibrary);
// Create new book to insert into libraries
BookNode currNode;
Book tempBook;
String bookTitle;
String bookAuthor;
long bookISBN;
bookTitle = scnr.nextLine();
bookISBN = scnr.nextLong();
scnr.nextLine();
bookAuthor = scnr.nextLine();
// Insert into linked list
currNode = new BookNode(bookTitle, bookAuthor, bookISBN);
// TODO
int i = linkedListLibrary.insertSorted(currNode,0);
linkedListLibrary.lastNode = currNode;
// Insert into ArrayList
tempBook = new Book(bookTitle, bookAuthor, bookISBN);
// TODO
int j = arrayListLibrary.insertSorted(tempBook,0);
// TODO: Print number of operations for linked list
System.out.println("Number of operations for linked list : "+i);
// TODO: Print number of operations for ArrayList
System.out.println("Number of operations for ArrayList : "+j);
}
}
// Book.java
public class Book{
private String bookTitle;
private String bookAuthor;
private long bookISBN;
public Book() {
bookTitle = "";
bookAuthor = "";
bookISBN = 0;
}
public Book(String userBookTitle, String userBookAuthor, long userBookISBN) {
bookTitle = userBookTitle;
bookAuthor = userBookAuthor;
bookISBN = userBookISBN;
}
public long getBookISBN() {
return bookISBN;
}
public void printInfo(){
System.out.println("Title: " + bookTitle);
System.out.println("Author: " + bookAuthor);
System.out.println("ISBN: " + bookISBN);
}
}
// ArrayListLibrary.java
import java.util.ArrayList;
public class ArrayListLibrary {
// ArraryList library
public ArrayList<Book> library;
public ArrayListLibrary() {
library = new ArrayList<Book>();
}
public int insertSorted(Book newBook, int counter) {
Book currBook;
// Add an empty element at end of list
library.add(null);
// Loop through elements starting at the end
for (int i = library.size() - 2; i >=0; --i) {
currBook = library.get(i);
// If the current book's ISBN is larger than newBook's ISBN, shift
// the current book down 1, count shift operation
if(currBook.getBookISBN() > newBook.getBookISBN()){
library.set(i+1, currBook);
++counter;
}
// Otherwise, place newBook at the next location (empty slot),
// count insert operation
else {
library.set(i+1, newBook);
++counter;
return counter;
}
}
// If we get to the top of the list, place newBook on top
library.set(0, newBook);
++counter;
return counter;
}
public void printLibrary() {
for (int i = 0; i < library.size(); ++i) {
library.get(i).printInfo();
System.out.println();
}
}
}
// BookNode.java
public class BookNode {
private String bookTitle;
private String bookAuthor;
private long bookISBN;
private BookNode nextNodePtr; // Reference to the next node
public BookNode() {
bookTitle = "";
bookAuthor = "";
bookISBN = 0;
nextNodePtr = null;
}
// Constructor
public BookNode(String bookTitleInit, String bookAuthorInit, long bookISBNInit) {
this.bookTitle = bookTitleInit;
this.bookAuthor = bookAuthorInit;
this.bookISBN = bookISBNInit;
this.nextNodePtr = null;
}
// Constructor
public BookNode(String bookTitleInit, String bookAuthorInit, long bookISBNInit, BookNode nextLoc) {
this.bookTitle = bookTitleInit;
this.bookAuthor = bookAuthorInit;
this.bookISBN = bookISBNInit;
this.nextNodePtr = nextLoc;
}
// insertAfter
public void insertAfter(BookNode nodeLoc) {
BookNode tmpNext;
tmpNext = this.nextNodePtr;
this.nextNodePtr = nodeLoc;
nodeLoc.nextNodePtr = tmpNext;
}
//setNext
public void setNext(BookNode nodeLoc) {
this.nextNodePtr = nodeLoc;
}
// Get location pointed by nextNodePtr
public BookNode getNext() {
return this.nextNodePtr;
}
public long getBookISBN() {
return this.bookISBN;
}
// TODO: Print book information
public void printBookInfo() {
System.out.println("Title: " + this.bookTitle);
System.out.println("Author: " + this.bookAuthor);
System.out.println("ISBN: " + this.bookISBN);
}
}
// LinkedListLibrary.java
public class LinkedListLibrary {
//Linked list nodes
BookNode headNode;
BookNode lastNode;
LinkedListLibrary() {
// Front of nodes list
headNode = new BookNode();
lastNode = headNode;
}
public int insertSorted(BookNode newNode, int counter) {
BookNode currNode, nextNode;
// Special case for head node
if (headNode == null || headNode.getBookISBN() >= newNode.getBookISBN()) {
newNode.insertAfter(headNode);
headNode = newNode;
}
else {
// Locate the node before insertion point
currNode = headNode;
while (currNode.getNext() != null && currNode.getNext().getBookISBN() < newNode.getBookISBN()) {
currNode = currNode.getNext();
}
newNode.setNext(currNode.getNext());
currNode.insertAfter(newNode);
}
++counter;
return counter;
}
public void printLibrary() {
BookNode currNode;
currNode = headNode.getNext();
while (currNode != null) {
currNode.printBookInfo();
System.out.println();
currNode = currNode.getNext();
}
}
}
Did the same lab. They make it seem intimidating with the amount of files and text thrown at you, but to pass the lab you just need to add the two lines to the end of Library.java:
System.out.println("Number of linked list operations: " + linkedListLibrary.insertSorted(currNode, linkedListOperations));
System.out.println("Number of ArrayList operations: " + arrayListLibrary.insertSorted(tempBook, arrayListOperations));
To explain:
The lab was to help you go through established code and read its set methods to learn how to do work in a class you haven't made. If you followed the development stubs (#TODO's) you would trace the path to finding what you need to do. This is what leads to the solution in this case!
I am creating a program to create a graph for bibliography dataset. The graph is directed, has Author node and Paper node, and has 2 types of edges (author to paper edge, paper to paper edge).
I want to get an input from you about whether or not what I am creating is making sense. Right now, it produces the right result when I want to get the outEdge and inEdge from and to a node. But im not sure if this implementation is correct in terms of the methods, designs, and algorithm.
Also, I have a problem with assigning weight to a node. I want to ask how can I do this as well. Right now, what I have tried is as follows:
for (String item : CandidateAuthorType1Unique) {
double weight = Collections.frequency(CandidateAuthorType1, item);
n.setWeight(item,weight);;
System.out.println(n.getName() + " : " + n.getWeight());
}
However, after using setWeight, the getName() method returns null. This means that the weight assigned is not assigned to a certain item. I wonder how to update the weight a certain item.
If I use
for (String item : CandidateAuthorType1Unique) {
double weight = Collections.frequency(CandidateAuthorType1, item);
n = new Node(item,weight);
System.out.println(n.getName() + " : " + n.getWeight());
}
Does it mean that each time a new node n is created, the old n node will not be stored? How can I checked every node ever created and its weight?
I would like to ask for your input to this program. Any input would be really helpful for me. Thank you.
Main class: Ranker.java
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.sql.*;
public class Ranker {
static Graph g;
static Node n;
static Edge e;
static HashMap nodeMap; // maps Integer NodeIDs to Node object
String id;
double weight;
Ranker() {
g = new Graph();
nodeMap = new HashMap();
n = new Node(id,weight);
}
public static void main (String[] args) throws ClassNotFoundException, SQLException, IOException, IllegalArgumentException, IllegalAccessException{
Ranker Ranker = new Ranker();
Connection connect = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
HashMap nodeMap = new HashMap(); // maps Integer NodeIDs to Node objects
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/arnetminer?"+"user=root&password=1234");
preparedStatement = connect.prepareStatement("Select fr,t,ty from subedge");
resultSet = preparedStatement.executeQuery();
int i=0;
while(resultSet.next()) {
g.addEdgeForIndexing(resultSet.getInt(1),resultSet.getInt(2),resultSet.getInt(3));
i++;
System.out.println( "edges added to G = "+i);
}
System.out.println("Loaded " + g.nodeCount() + " nodes.");
buildNodes();
System.out.println("Enter first author key:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String authorkey1 = br.readLine();
int authorID1 = Integer.parseInt(authorkey1);
String AuthorID1 = "A"+authorID1;
ArrayList<String> p1 = g.getOutEdgesToP(AuthorID1);
System.out.println("P1 = " + p1);
ArrayList<String> p2 = new ArrayList<String>();
for (int j = 0; j<p1.size();j++){
ArrayList<String> temp = g.getOutEdgesToP(p1.get(j));
if (temp!=null)
p2.addAll(temp);
}
System.out.println("P2 = " +p2);
ArrayList<String> CandidateAuthorType1 = new ArrayList<String>();
for (int k = 0; k<p2.size(); k++){
ArrayList<String> temp = g.getInEdgesFromPtoA(p2.get(k));
if(temp!=null)
CandidateAuthorType1.addAll(temp);
}
System.out.println("Candidate Author Type 1= " + CandidateAuthorType1);
ArrayList<String> CandidateAuthorType1Unique = removeDuplicates(CandidateAuthorType1);
System.out.println("-----------------------------------------------");
System.out.println("Candidate author type 1 and author node weight:");
for (String item : CandidateAuthorType1Unique) {
double weight = Collections.frequency(CandidateAuthorType1, item);
n.setWeight(item,weight);;
System.out.println(n.getName() + " : " + n.getWeight());
}
ArrayList<String> CandidatePaperType1 = new ArrayList<String>();
for (int l = 0; l<CandidateAuthorType1.size(); l++){
ArrayList<String> temp = g.getOutEdgesToP(CandidateAuthorType1.get(l));
if(temp!=null)
CandidatePaperType1.addAll(temp);
}
System.out.println("Candidate Paper Type 1= " + CandidatePaperType1);
}
private static ArrayList<String> removeDuplicates(ArrayList<String> element){
ArrayList<String> result = new ArrayList<>();
HashSet<String> set = new HashSet<>();
for (String item : element) {
if (!set.contains(item)) {
result.add(item);
set.add(item);
}
}
return result;
}
private static void buildNodes()
{
String nodeID;
double weight = 0;
Node n;
Iterator it = g.nodeIteratorInitial();
while (it.hasNext()) {
nodeID = (String) it.next();
if (!nodeMap.containsKey(nodeID)){
n = new Node(nodeID,weight);
nodeMap.put(nodeID, 0);
}
}
}
}
Graph.java
import java.lang.reflect.Field;
import java.util.*;
public class Graph {
private HashSet<String> nodeIDs;
public HashMap<Integer, String> nodeIDsWithTN;
public HashMap<Integer, String> TNMap;
private HashMap<String, ArrayList<String>> edges;
private HashMap<String, ArrayList<String>> reverse;
private int numNodes;
private int numEdges;
private int numReverse;
public Graph() {
edges = new HashMap<String, ArrayList<String>>();
reverse = new HashMap<String, ArrayList<String>>();
nodeIDs = new HashSet<String>();
nodeIDsWithTN = new HashMap<Integer, String>();
TNMap = new HashMap<Integer, String>();
new HashSet();
}
public void addEdgeForIndexing(int from, int to, int T) throws IllegalArgumentException, IllegalAccessException {
String From = ""+from;
String To = ""+to;
int type = T;
if(T==1)
{
From="A"+from;
To="P"+to;
}
else if(T==2)
{
From="P"+from;
To="P"+to;
}
else
System.out.println("T ="+T+" value undefined");
Edge e = new Edge(From,To,type);
nodeIDs.add(e.From);
nodeIDs.add(e.To);
ArrayList<String> tmp = null;
if (edges.containsKey(e.From))
tmp = (ArrayList<String>) edges.get(e.From);
else {
tmp = new ArrayList<String>();
edges.put(e.From,tmp);
}
tmp.add(e.To);
ArrayList<String> tmp2 = null;
if (reverse.containsKey(e.To))
tmp2 = (ArrayList<String>) reverse.get(e.To);
else {
tmp2 = new ArrayList<String>();
reverse.put(e.To,tmp2);
}
tmp2.add(e.From);
}
public int nodeCount() {
if(nodeIDs.size() > 0)
return nodeIDs.size();
// else return numNodes;
return numEdges;
}
public int countInEdges(Integer key) {
if (!reverse.containsKey(key)) return 0;
return ((ArrayList<?>) reverse.get(key)).size();
}
public int countOutEdges(Integer key) {
if (!edges.containsKey(key)) return 0;
return ((ArrayList<?>) edges.get(key)).size();
}
public ArrayList<String> getInEdgesFromPtoA(String id) {
if (!reverse.containsKey(id)) return null;
ArrayList<String> a = reverse.get(id);
ArrayList<String> result = new ArrayList<String>();
for(int j=0;j<a.size();j++){
if(a.get(j).startsWith("A")){
result.add(a.get(j));
}
}
return result;
}
public ArrayList<String> getOutEdgesToP(String id) {
if (!edges.containsKey(id)) return null;
ArrayList<String> a = edges.get(id);
ArrayList<String> result = new ArrayList<String>();
for(int j=0;j<a.size();j++){
if(a.get(j).startsWith("P")){
result.add(a.get(j));
}
}
return result;
}
public Iterator<String> nodeIteratorInitial() {
return nodeIDs.iterator();
}
}
Edge.java
public class Edge {
String From;
String To;
int type;
private static int counter = 0;
public Edge(String From, String To, int type) {
this.From = new String(From);
this.To = new String(To);
this.type = type;
// System.out.println("edges added from " + From + " to " + To + " with type "+ type);
}
public String getFrom(){
return From;
}
public String getTo(){
return To;
}
public int getType(){
return type;
}
public void setFrom(String From){
this.From = From;
}
public void setTo(String To){
this.To = To;
}
public void setType(int type){
this.type = type;
}
}
Node.java
public class Node {
String id;
double weight;
private static int counter = 0;
public Node(String id,double weight) {
this.id = id;
this.weight = weight;;
}
public double getWeight(){
return weight;
}
public String getName() {
return id;
}
public void setWeight(String id, double weight){
if (this.id==id){
this.weight=weight;}
System.out.println("The node " + id + " has weight " + weight);
}
public void setName(String id){
this.id=id;
}
}
As you are initialising n in the Ranker() constructor, when the constructor is called, the String id has not been assigned and therefore always contains the value null. Therefore your Node n also gets the id as null. This is the reason why the weight isn't updated as in your setWeight(String id, double weight) function, the new id is compared to null which always returns false therefore the weight doesn't get updated.
You could make the following changes in your code
1) Remove the n = new Node(id,weight) initialisation in your Ranker() constructor.
2) Add the following lines instead of n.setWeight(item,weight) in your main method in Ranker class.
if (n == null)
n = new Node(item, weight);
n.setWeight(item, weight);
I'm trying to create a Node class and I want the default to be all 0's and null and then when I call the node class with constructors i want to set them. and with the code I have set now I just keep getting
symbol: method Node(int,int,java.lang.String)
location: variable n1 of type Node
I don't understand what's wrong with my default constructor cause it will only work when I delete it.
class Node{
private int ticks;
private int jobId;
private String name;
private Node next;
public Node(){
next = null;
ticks = 0;
jobId = 0;
name = " ";
}
public Node(int t,int j, String name){
ticks = t;
jobId = j;
name = name;
}
//sets next to node
public void setNext(Node next){
next = next ;
}
}//end class node
MAIN---------------------------------------------------------
public class lab3{
public static void main(String[] args) throws Exception{
//Open File
File file = new File("p3.dat");
Scanner in = new Scanner(file);
int jobId = storeJobIdNum(in);
int ticks = storeTicks(in);
String name = storeName(in);
Node n1 = new Node();
n1.Node(ticks,jobId,name);
jobId = storeJobIdNum(in);
ticks = storeTicks(in);
name = storeName(in);
// String line = in.nextLine();
// String name = line;
//System.out.println(jobId+" "+num+" "+numTicks);
// n1.setNode(,,);
}//end main
public static String storeName(Scanner in){
String name = in.next();
System.out.println(name);
return name;
}
public static int storeJobIdNum(Scanner in){
int num = in.nextInt();
System.out.println(num);
return num;
}
public static int storeTicks(Scanner in){
int num = in.nextInt();
System.out.println(num);
return num;
}
}//end class
p3.dat looks like ==> 1 4 name
and has a few lines that differ.
Once the object is created, you won't be able to invoke another constructor with it. Instead, create a method that takes care of changing the fields.
Put this as your method call to set the attributes:
Node n1 = new Node();
n1.set(ticks,jobId,name);
And then in Node, use this instead of another constructor:
public void set(int t,int j, String name){
this.ticks = t;
this.jobId = j;
this.name = name;
}
You'll generally hear these be called "setter" methods.
I am trying to read the input from a text file using scanner class and pass into an array. I know how to read the input using scanner class. The only problem I am facing here is I am unable to pass into the array.
public class ReadItemData {
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader(
"src//chapter11//Items.txt"));
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
System.out.println(code + " " + sku + " " + qty);
}
}
The above code works without the array concept. I want to extend the same concept to read the above data into a array of size 100. Any suggestions would be helpful. My final aim is to sort the input which is in array by code,sku
This is how I used comparable interface for sorting. How can I extend this concept for arrays?
I used something like this for sorting(without the array concept)
class Item implements Comparable {
private int qty;
private String sku,code;
public Item(int qty, String sku,String code) {
this.qty = qty;
this.sku = sku;
this.code = code;
}
public int getQty() {
return qty;
}
public String getSku() {
return sku;
}
public String getCode() {
return code;
}
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getQty() < i.getQty())
{
return -1;
}
if (this.getQty() > i.getQty())
{
return 1;
}
return 0;
}
}
Thanks!!
String[] array = new String[100];
int currentIndex = 0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[currentIndex] = code;
array[currentIndex++] = sku;
array[currentIndex++] = ""+qty;
currentIndex++;
}
As mentioned in the comments, you can use 2D array of 100 rows and 3 columns like this:
Object[][] array = new Object[100][3];
int i=0,j=0;
while (aScanner.hasNext()) {
String code = aScanner.next();
String sku = aScanner.next();
double qty = aScanner.nextDouble();
array[i][j++] = code; // array of row i and columns j
array[i][j++] = sku;
array[i][j] = qty;
i++; // increment i since it's for rows
j=0;//reset j because it's for columns
}
I have a String exp, which I have to compare with the mapsList.
String exp = "nodeId=1&&name=Router||level=1";
List mapList = new ArrayList();
Map map = new HashMap();
map.put("nodeId","1");
map.put("name","Router");
map.put("level", "1");
Map map1 = new HashMap();
map1.put("nodeId","2");
map1.put("name","Router");
map1.put("level","2");
Map map2 = new HashMap();
map2.put("nodeId","3");
map2.put("name","Router");
map2.put("level","3");
mapList.add(map);
mapList.add(map1);
mapList.add(map2);
I take the exp and split into an array.
String delims = "[\\&&\\||\\=]+";
String[] token = exp.split(delims);
Then I divide the array into two smaller sub arrays. One for Keys and the other for values. After which I compare ...
if(map.keySet().contains(a1[0]) && map.keySet().contains(a1[1]) || map.keySet().contains(a1[2])){
if(map.values().contains(a2[0]) && map.values().contains(a2[1]) || map.values().contains(a2[2])){
System.out.println("Match\tMapKeys: "+map.keySet()+" Values: "+map.values());
}else{
System.out.println("No Match\t");
}
}
So my problem is I can do this for each map, but can't figure out how to implement it with iterator.
Can some1 push me in the right direction?
Thanks.
You really, really want to define an object to hold your data, instead of using HashMaps.
class Node {
private int id;
private String name;
private int level;
public Node(int id, String name, int level) {
this.id = id;
this.name = name;
this.level = level;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getLevel() {
return level;
}
}
now you populate the list like this
List<Node> nodeList = new ArrayList<Node>();
nodeList.add(new Node(1, "Router", 1));
nodeList.add(new Node(2, "Router", 2));
nodeList.add(new Node(3, "Router", 3));
and you could look for your match like this
String exp = "nodeId=1&&name=Router||level=1";
String delims = "[\\&&\\||\\=]+";
String[] token = exp.split(delims);
int id = Integer.parseInt(token[1]);
String name = token[3];
int level = Integer.parseInt(token[5]);
boolean match = false;
for (Node node : nodeList) {
if (node.getId() == id && node.getName().equals(name)
&& node.getLevel() == level) {
System.out.println("Match found: " + node);
match = true;
}
}
if (!match) {
System.out.println("No match");
}
which gives me the following output
Match found: Node#1391f61c
and the next step is to implement toString.
You should check out http://docs.oracle.com/javase/tutorial/java/concepts/ as it introduces objects and why they are useful.