Breadth First Search - How To Iterate Through ArrayList

Aug 18, 2014

I have done this before in C++ but now I want to do it in Java. I am not sure how to iterate through a ArrayList, I have look several places because lets be honest the first stop is normally google. I tried the examples but with no luck.
 
for(auto it= foo.begin(); it!= foo.end(); foo++) {
*it //do something.
}

Here is the program:
 
package org.search.BFS;
import java.util.Queue;
public class BFS extends Graph {
private Queue<Integer> q;
BFS(int s) {
//mark all the vertices as not visited.

Also the below is giving me a Type safety: The expression of type ArrayList[] needs unchecked conversation to conform to ArrayList<Integer>[]

adj = new ArrayList[V];

What does this mean?

View Replies


ADVERTISEMENT

Implementing Breadth First Search

Dec 13, 2014

I have always wanted to program A*, Breath First Search and Depth First Search ever since I took AI. I will only post BFS at the moment but it is only searching the row.

Java Code:

//Breath First Search. The first node passed to it is the start button
void bfs(Mybuttons button){
Queue<Mybuttons> q = new LinkedList<Mybuttons>();
q.add(button);
button.setIcon(button.setButtonToBlueWhileSearched());
button.model.visted=true;

[Code] ....

Output:

Java Code: In while loop
In get Child Node
In get Child Node
In get Child Node
In get Child Node
In while loop
In get Child Node
In get Child Node
In get Child Node
In while loop
In get Child Node
In get Child Node
In while loop
In get Child Node mh_sh_highlight_all('java');

View Replies View Related

Breadth First Search Traversal

Dec 5, 2014

This method uses BFS traversal on a vertex and displays the values. I have worked this out on paper and 2 out of 3 the results from my code match my work on paper. I believe the error is that it prints out 3's adjacent child before 3 itself. I have attached the results I did by hand. Here's the graph and results from my code:

0 1 2 3 4 5
------------
0| 0 1 1 0 0 0
1| 0 0 0 0 0 0
2| 0 0 0 1 0 0
3| 1 0 0 0 0 0
4| 0 0 1 0 0 1
5| 0 1 0 1 0 0

BFS:
5 1 3 0 2
4 2 5 0 3 1 //i think this is wrong. shouldnt it be 4 2 5 3 1 0?
0 1 2 3

Here is my code:

public void bfsTraversal(int vertex){
Queue<Integer> q = new LinkedList<Integer>();
visited[vertex] = 1;//mark vertex as visited
q.add(vertex);
System.out.print(vertex + " ");

[Code] .....

Attached image(s)

View Replies View Related

Learning To Iterate A List And Search Through Another

May 5, 2015

I am learning iterating through lists. What I have so far is two Hash Sets and two Tree sets. Hash Set 1 and Tree set 1 include the words from Roughing it by Mark Twain. Hash set 2 and tree set 2 include the words from Adventures of Huckleberry Finn by Mark Twain. (Everything is read from a file I made).

I am stuck trying to find out how to "Iterate through the words in HashSet1 and search for these words in both TreeSet2 and in HashSet2".Here is my code:

public class UsingSets {
public static void main(String[] args) throws FileNotFoundException {
String riHashIterator = null;
HashSet<String> riHash = new HashSet<>();
Scanner input = new Scanner(new File("roughingit.txt"));
while(input.hasNext()){
String riHashWords = input.next();
riHashWords = riHashWords.toLowerCase();
riHash.add(riHashWords);

[code]....

View Replies View Related

Linear Search Of Arraylist By Last Name

Nov 5, 2014

I am having some trouble with linear search of a customers last name. I can't seem to get it to work. I have looked up examples but cant find many with Array Lists. Here is my code.

import java.util.ArrayList;
import java.util.Scanner;
public class AccountDriver {
public static void main(String[] args) {
ArrayList<Account> al = new ArrayList<Account>();
ArrayList<Customer> cust = new ArrayList<Customer>();
Scanner scan = new Scanner(System.in);

[code]....

View Replies View Related

EJB / EE :: How To Search Items In ArrayList

Jan 26, 2015

I try to create a jsf project within ejb which is add new car with entering attributes listing attributes and search by make.

Add and list methods working well , but have problem of list method. I tryed many combinations (using enhanced loop, iterative loop) but i cant provide working well. Always outputText returns nothing ,when i enter attributes.

Here is ejb code for adding ,getting and listing car items :

@Stateful
public class CarsBusiness implements CarsBusinessLocal {
List<Car> cars;
public CarsBusiness() {
cars = new ArrayList<Car>();

[Code] .....

View Replies View Related

Traverse ArrayList To Search For Integer Key

Oct 14, 2014

I am very new to coding and I am struggling with one of my intro to Java Projects. This project involves creating a GUI that has a list of trees and their possible heights, giving each tree a range for their possible minimum and maximum heights.

I am having trouble creating this method for the TreeDatabase (TreeDB class):

public String queryByPossibleHeight(int key) Instructions for this method are as follows: this method creates and returns a single string that contains the trees that can be found such that the value key is in the range for possible height. Traverse the entire ArrayList of Trees and for each one of the trees contained in the ArrayList invoke the method inRange() from the class Tree. Pass to the method inRange() the parameter key. If inRange() returns true, invoke the method toString() from the class Tree. Append the value returned by invoking the method toString() to the String result, adding a “” at the end. Once the entire ArrayList has been traversed, return the String result.

My 3 classes so far (I haven't gotten to the actual GUI yet):

public class Range {
private int low;
private int high;
private int value;
public Range(int plow,int phigh){
low = plow;
high = phigh;

[Code]...

As you can see in the last TreeDB class, in the public String queryByPossibleHeight(int key) method I have something wrote in, but I was just testing random things.

View Replies View Related

Searching ArrayList - Cannot Find Symbol For Search Method

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

How To Implement Collections Binary Search Method On ArrayList Of Custom Objects

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

Ability To Search A Binary Search Tree And Return The Number Of Probes

Sep 1, 2014

I'm trying to build a method that can search a binary search tree for a specific target and then return the number of probes it took to get there. It seems to me that the best way to do this would be a recursive search method and a counter that tracks the number of calls. But I'm struggling with how to implement this. Here's the code I have so far. what works/doesn't work with the method.

// Method to search the tree for a specific name and
// return the number of probes
public T search(BTNode<T> btNode) {

[Code]....

View Replies View Related

Creating Search Method For Binary Search Tree

Apr 22, 2014

I want to create a search method that returns the frequency of a word in the search method.

public class IndexTree {
private class TreeNode {
TreeNode left;
String word;
int frequency;
TreeNode right;

[Code] .....

View Replies View Related

Iterate Through Objects

Feb 27, 2015

I would like to know how I can iterate through objects . I have a manually created linked list (without using the built-in method one). So in the memory my object looks like this(attachment).I would like to do a for loop or while loop to get each element under the test3.head.

View Replies View Related

How To Iterate Two Lists At A Time

Mar 25, 2015

List list1 = query1.list();
List list2 = query2.list();
 
for (Iterator itr = list1.iterator(); itr.hasNext();) {
Object[] row = (Object[]) itr.next();
}

View Replies View Related

Iterate Through Multimap By Compare

Mar 22, 2014

I've a contents in multimap like this,

key, value

{Name=[Amit, Akash, Amulya, Aparna, Angle],
Mail_Id=[amit@gmail.com, akash@gmail.com, amulya@gmail.com, aparna@gmail.com, angle@gmail.com]
Gender=[male, male, Female, female, female],
Age=[14, 15, 16, 17, 18]
}

Now, I want to display it like this,

Name = Amit
Mail_Id=amit@gmail.com
Gender=male
Age=14

Name = Akash
Mail_Id=akash@gmail.com
Gender=male
Age=15

Name = Amulya
Mail_Id= amulya@gmail.com
Gender=Female
Age=16

Name = Aparna
Mail_Id=aparna@gmail.com
Gender=Female
Age=17

Name = Angle
Mail_Id=angle@gmail.com
Gender=Female
Age=18

I mean, Each first element matches to first element of the next key. How to do this?

View Replies View Related

How To Iterate Through Linked Lists And Add Them To A Map

Mar 10, 2014

I have an XML sheet and my project is top retrieve the required elements from XML sheet. So my format of XML was like follows:

<Class>
<Employees>
<EMPLOYEE>
<ENum> Abc123</ENum>
<Ename> John<?Ename>
<EType>Mathematics</EType>

[Code] ....

I have used unmarshalling concept to retrieve the data elements... I have to check whether the elements satisfy few regulations when compared with data in Database. So, i thought of grouping the employees depending on EType. I have created a Map with linkedlist of employees. Say Map<String, LinkedList<Employe>>EmpMap=new Map<String, LinkedList<Employe>>();

I have already created a class named Employee which has all the setter and getter methods for employee.

Here am going to take Etype(Employee type) as key and linkedlist(list of employees of certain type) as value. How to iterate these linked lists and place them in my Map.

View Replies View Related

JSP :: How To Iterate Over Supplied Items

Mar 11, 2014

I facing issue with nested <c:forEach in my jsp page.I am using jstl.jar..Here is my code

in JAVA I have -->
List<ProductDefViewBean> productList = new ArrayList<ProductDefViewBean>();
productList.add(objProductDefViewBean);
request.setAttribute("ProductList", productList);
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

[code]...

javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>

View Replies View Related

I/O / Streams :: How To Iterate Over Files In A Directory One By One

Oct 5, 2014

Requirements - Use only standard Java API and no apache file utils for this.

Most of the answers I found on the internet either dont meet this requirement or load all file names into an array which can consume too much memory when no. of files = 20,000+. how I can do this. Is there also a way to keep track of new files that were added during the execution of the loop in this code ?

View Replies View Related

Iterate Over List And Get Values From Object?

Jan 22, 2015

first i looked at this example and understand this fine:

import java.util.ArrayList;
import java.util.Iterator;
public class Main {

[Code]....

View Replies View Related

JSP :: Code To Iterate Excel File?

May 6, 2014

I have a JSP code which will open the contents of a excel file.

Now i need this contents of the excel file to be added dynamically to a table in the sameJSP. How to proceed.At the maximum 10 rows can be added dynamically.

Assuming i have a table in JSP which has heading first name,last name,DOB and Gender. After opening the excel through JSP the contents needs to be iterated and added to the columns mentioned.

View Replies View Related

Iterate Enum Type Without Instance

Sep 16, 2014

Is there anyway to iterate an enum type without an instance. As some context, consider the following code:

Java Code: public interface GenericChecker
{
public bool isValid(String str);
} mh_sh_highlight_all('java'); Java Code: public class EnumChecker<T extends Enum<T> > extends GenericChecker
{
private Class<T> enumType; //No instance

[code]....

toString method of the enum types has been overridden so that it returns the name assigned to the enum rather than the enum name itself. For example an enum might be SOME_ENUM("Assigned name"), therefore toString returns "Assigned name" rather than "SOME_ENUM". The idea is that a field from a table can be handed to the isValid(String) function on the GenericChecker base, and the derived class will then check to see if the field matches valid data as far as it is concerned.Thus, I can create a whole bunch of checkers easliy:

Java Code: GenericChecker checker1 = EnumChecker<EnumType1>();
GenericChecker checker2 = EnumChecker<EnumType2>();
GenericChecker checker3 = EnumChecker<EnumType3>();
GenericChecker checker4 = SomeOtherChecker(); mh_sh_highlight_all('java');

The problem is, if I use the EnumChecker then the expression "enumType.getEnumConstants()" in the isValid function blows up because enumType is null.

View Replies View Related

Array - How To Iterate Through Only Values Greater Than 0

Feb 9, 2014

I have an 46x9 array. I only have 108 values in the array for which I need to perform preliminary computations. How do I get the read to only read the 108 values whose values are greater than 0 and skip the other 495 whose values are 0?

View Replies View Related

Trying To Iterate Though Array To Display Value In Calculator

Apr 20, 2014

my getDisplayValue() method. I am trying to iterate though an Array to display a value in a calculator, but I doesn't work. I keep on getting these weird magical numbers at the end of the iteration. Note that this is done in BlueJ.

Calculator -> UserInterface -> CalcEngine and Calculator -> CalcEngine.
public class CalcEngine
{
//Instance variables used.
//These are all the instance variables I used to implement
//a complete calculator solution.
 
[code]...

View Replies View Related

Iterate Linked List And Map With Properties File Value

Jan 22, 2014

I have `country.properties` file which have values as follows:

1=USA
91=India
20=Egypt
358=Finland
33=France
679=Fiji

and, have a response class file, which is setting a response from database to display it on `JSP` file. The value that I am getting from database is in the form of `code` or `integer`. I needed to have that value from the database and before setting the response I need to use `getProperty(code)` and save the String representation of that code into a new list and then pass that list to `setResponse`. For e.g: This is the value I am getting from database:

col1 | col2 | col3 |
1 helo done

I needed to show on my JSP page as:

col1 | col2 | col3 |
USA helo done

I was following this tutorial [URL].... but not able to exactly understand how to achieve the same.

This is my `DAOImpl` where I needed to `iterate` and save the `mapped key-value` in a new list and then pass to `JSP` page

public class CountDAOImpl implements IDataDAO {
private Connection conn = null;
private Statement statement = null;
private ResultSet rs = null;
private List<String> country_code = new LinkedList<String>();

[Code] ....

View Replies View Related

Java Iterate Over Collection Not Working As Expected

Aug 6, 2014

I am currently working on a Java project, below are my attempts at coding so far:

public class MyZoo
{
// zoo identifier
private String zooId;
// a number used in generating a unique identifier for the next animal to be added to the zoo
private int nextAnimalIdNumber;
// zstorage for the Animal objects
private TreeMap<String, Animal> animals;

[Code] ....

I currently cannot get the printAllAnimals() method to work as it should.

When executing the method printAllAnimals(), it does not do anything, when it is supposed to use the Collection object c, so that animals stored in the zoo can easily be checked.

View Replies View Related

JSP :: Iterate And Populate Values Of TXT File Into Text Area

May 15, 2014

How can I read a text file present in my local directory say (C://test.txt) , iterate and populate the values of test.txt into a text area of the JSP page?

Contents in the test.txt file:
username:test
password:test123
domain:test321
DBname:testDB

View Replies View Related

Create Own ArrayList Using Collection Without Implementing ArrayList Itself

Feb 28, 2014

I'm trying to create my own arraylist using Collection. My program doesn't do anything. Obviously, I haven't a clue.

import java.util.Collection;
import java.util.Iterator;
public class MyArrayList<T> implements java.util.Collection<T> {
private int size = 4;
private T[] mArray;
public MyArrayList(String[] args) {

[Code] ....

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved