How To Use Iterator Instead Of Foreach Loop
Mar 25, 2015
I am trying to use an iterator instead of a foreach loop to go through a list of inventories to see if a car is rearDrive and count how many are rearDrive but somehow I seem to be missing something that the counter isn't working as expected.
public int howManyAreRearWheelDrive(){
int i = 0;
int counter = 0;
int inventSize = inventory.size()-1;
while(i < inventSize){
boolean wheelDrive = inventory.get(i).getIsRearWheelDrive();
if( wheelDrive == true){
counter++;
}
}
return counter; // returning here doesn't give me anything
}
View Replies
ADVERTISEMENT
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
Oct 7, 2014
I've implemented Stack on the base of the LinkedList. It works as i expect it to work, but then i tried to made it compatible with foreach loop. I've implemented Iterable and Iterator. Code compiles and works fine, but does not return any output. It looks like while working with foreach, next() is not called at all. If i`m getting iterator from instance and try to do iterator.next(), i get output as expected.
public class genericStack<T> implements Iterator<T>, Iterable<T> {
private LinkedList<T> LL ;
protected genericStack() {
this.LL = new LinkedList<T>();
}
public static void main(String[] args) {
[Code] ....
View Replies
View Related
Nov 4, 2014
I have a ace:dataTable which contains a variable number of columns. For this I use the c:forEach tag. All generated in the c:forEach are not displayed. In the sample, only columnLibelle and columnSum are displayed.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
[Code] ....
View Replies
View Related
Apr 26, 2015
I am trying display the result set from the database.I am getting the following exception :
Caused by: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.toForEachIterator(ForEachSupport.java:286)
My Jsp code :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
[Code] ....
View Replies
View Related
Apr 4, 2014
I need to find out if one array list is a sub-sequence of another. The elements in the first list all need to be in the second list and must be in the same order. So s1<n, t, a> is a sub-sequence of s2<q, n, f, r, t, d, a>, but s1<a, a, t> is not a sub-sequence of s2<a, t, a>. I need to use iterators to go through each list, and I should only go through each list once (since it has to be in the same order) so nested loops don't seem like they would work because it would start at the beginning of one list every time it moved to another element in the outer loop's list.I seem to have an issue where the itr1. next()
is ignored when in an if statement.
My current code just stalls and will never stop running. I've also switched things around and put the not equal check after the if it is equal and it throws a NoSuchElementException.
import dataStructures.*;
public class Subsequence3
{
public static void main(String[] args)
{
ArrayList<Character> s1 = new ArrayList<Character>();
s1.add('n');
s1.add('p');
s1.add('a');
[code]....
View Replies
View Related
Nov 12, 2014
I am trying to add the contents of the iterator to an arraylist so I can do other stuff to it, however I am getting an error when I actually try adding it to the list, stating that
"The method add(Map.Entry<String,myObject>) in the type ArrayList<Map.Entry<String,myObject>> is not applicable for the arguments (myObject)"
Here is what I have tried doing:
Iterator<Map.Entry<String, myObject>> iterator = hash.entrySet().iterator();//hash is my HashMap object
ArrayList<Map.Entry<String, myObject>> list = new ArrayList<Map.Entry<String, myObject>>();
while(iterator.hasNext()){
Map.Entry<String, myObject> entry = iterator.next();
list.add(entry.getValue());//error here
}
View Replies
View Related
Feb 24, 2014
The Iteratior provides the functionality of traversing and removal which we can achieve through normal for loop and remove() of the data structure.Then, why do we need Iterator explicitly and as an inner class?
View Replies
View Related
Mar 3, 2014
What does the iterator() method return???it can't return an object of Iterator as it's an interface...
View Replies
View Related
Feb 8, 2015
As part of a homework assignment in my 1st Java Class, I am creating my own Circular Generic LinkedList and Array class. My class uses the Queue Interface Extends Iterable but I am creating my own methods to work with. For the most part, I believe I have been successful in creating the class aside from one method. That method is the Iterator<E> iterator().
/**
* Return a fail-fast iterator, which throw a java.util.ConcurrentModificationException
* if the client modifies the collection (via enqueue(...) or dequeue()) during iteration.
*/
@Override
public Iterator<E> iterator() {
I don't understand how an iterator, let alone a "fail-fast" iterator ties into my project. I've spent hours reading up on a way to imploy my own generic fail-fast iterator but to no avail.
I feel like I could come up with some workable code if I knew what the point is to useing a user-defined, non Java Library iterator is to do.
As well, does throwing a ConcurrentModificationException require a try and catch block?
View Replies
View Related
May 3, 2014
I have a problem with a linked list iterator, my problem is implementing the iterator.remove method given the following code:
package mapsql.util;
import java.util.Iterator;
public class LinkedList<T> implements List<T> {
private class Node implements Position<T> {
T element;
Node next, prev;
public Node(T element) {
this.element = element;
[Code] ....
View Replies
View Related
Mar 12, 2015
I am tring to run LDA to generate some topics from txt files as the following one:
Document1 label1 forest=3.4 tree=5 wood=2.85 hammer=1 colour=1 leaf=1.5
Document2 label2 forest=10 tree=5 wood=2.75 hammer=1 colour=4 leaf=1
Document3 label3 forest=19 tree=0.90 wood=2 hammer=2 colour=9 leaf=4.3
Document4 label4 forest=4 tree=5 wood=10 hammer=1 colour=6 leaf=3
Each numeric value in the file is an indication of the number of occurrences of each feature (e.g., forest, tree) multiplied by a given penalty. To generate instances from such a file, I use the following Java code:
String lineRegex = "^(S*)[s,]*(S*)[s,]*(.*)$";
String dataRegex = "[p{L}([0-9]*.[0-9]+|[0-9]+)_=]+";
InstanceList generateInstances(String dataPath) throws UnsupportedEncodingException, FileNotFoundException {
ArrayList<Pipe> pipeList = new ArrayList<Pipe>();
pipeList.add(new Target2Label());
[Code] .....
I then add the so-generated instances to my model using the instruction model.addInstances(generatedInstances). The resulting output is described below.
It contains errors caused by the instruction model.addInstances(generatedInstances). Debugging my code showed me that the alphabet associated to the model is null. Am I using the wrong iterator?
name: document1
target: label1
input: TokenSequence [forest=3.4 feature(forest)=3.4 span[0..10], tree=5 feature(tree)=5.0 span[11..17], wood=2.85 feature(wood)=2.85 span[18..27], hammer=1 feature(hammer)=1.0 span[28..36], colour=1 feature(colour)=1.0 span[37..45], leaf=1.5 feature(leaf)=1.5 span[46..54]]
Token#0:forest=3.4 feature(forest)=3.4 span[0..10]
[Code] ....
View Replies
View Related
Feb 17, 2015
I have the following HashMap:
// 2009
nobelPrizeWinners.put("2009 Physics",
new PrizeWinner[] {new PrizeWinner("Charles K.", "Kao"),
new PrizeWinner("Willard S.", "Boyle"), new PrizeWinner("George S.", "Smith")});
nobelPrizeWinners.put("2009 Chemistry",
new PrizeWinner[] {new PrizeWinner("Venkatraman", "Ramakrishnan"),
[Code] .....
At the moment, my output is:
2008: Chemistry: Osamu Shimomura, Martin Chalfie, Roger Y. Tsien
2008: Economics: Paul Krugman
2008: Literature: Jean-Marie Gustave Le Clézio
2008: Medicine: Harald zur Hausen, Françoise Barré-Sinoussi, Luc Montagnier
2008: Peace: Martti Ahtisaari
[Code] .....
However, I need a blank line between the final entry of 2008 and the first entry of 2009.
View Replies
View Related
Oct 14, 2014
My homework is a Double Circular Link list and when i write implements Iterator it gives me a an error when I compile it the same for my subset method...
ERRORS :DoublyCircularList.java:55: error: DoublyCircularList.iterator is not abstract and does not override abstract method remove() in Iterator public class iterator implements Iterator<T>
^
Note: DoublyCircularList.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
import java.util.Iterator;
public class DoublyCircularList<T extends Comparable<T>> extends LinkedList<T>implements Iterable<T>
{
Node<T> first;
int size;
public DoublyCircularList(){
first = null;
size = 0;
[code]....
View Replies
View Related
Nov 5, 2014
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
list.add(i * 3);
}
ListIterator<Integer> listItr = list.listIterator();
System.out.println("Traversing in a forward direction");
[Code] ....
Output:--
Traversing in a forward direction
0 3 6 9 12
Traversing in a backward direction
12 9 6 3 0 425
Why 425 is not showing when we are traversing in a forward direction.
View Replies
View Related
Sep 23, 2014
I'm not new to java but i'm not able to solve the following issue: I have a class
public class Localizzazioni implements java.io.Serializable {
private <complexType> id;
public getId().......
public setId().....
The complexType is a class defined in the code somewhere. Now I want to access it in another class I have
Set localizzazioni = new HashSet(0);
localizzazioni=opere.getOiLocalizzazioneOperas(); -- this object give an object of tyoe HashSet
for(Object object : localizzazioni) {
object.get......... // i cannot use any method defined in the class Localizzazioni
}
Why I cannot write inside the for object.getId() and using it?? In other word how i can access the element contained in the object?? the object is an iterator of type Localizzazioni . The class Localizzazioni has some method but i cannot use them? why ....
View Replies
View Related
Apr 14, 2015
I have been researching the Iterator and making a class implement iterable. I have seen this example shown below and was wondering how I could change this so that iterable() is not called upon in the main. I would like to be able to make a method that returns an instance of a class that implements the Iterator interface hopefully an inner class. This is because my program will not have a main and will be supplied with a main that includes a new Object with will use the iterator method.
import java.util.*;
public class IteratorDemo {
public static void main(String args[]) {
// Create an array list
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
[Code] ....
This is all I have been able to understand from what I want to do. This does not work and this is what I am trying to achieve
public class MyArrayList implements Iterable {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
[Code] ...
View Replies
View Related
Jan 27, 2015
I am trying to print a loop inside an array of a greater size than the loop itself. Like for example I have an array of size 7 but it has only 3 elements.
int[] array=new int[7]
array[0]=2;
array[1]=3;
array[2]=4;
now what I want to do is print these three numbers in a loop so that my array[3]=2;array[4]=3;array[5]=4 ...... till the last one. Also the array could be any size and not just 7.
View Replies
View Related
Feb 25, 2014
Here's the code: it's while loop inside a for loop to determine the proper length of a variable:
for (int i = 0; i < num; i++) {
horse[i]=new thoroughbred();
boolean propernamelength = false;
while (propernamelength==false){
String name = entry.getUserInput("Enter the name of horse "
[code]....
I was just wondering what was going on here -- I've initialized the variable, so why do I get this message? (actually the carat was under the variable name inside the parentheses.
View Replies
View Related
Nov 2, 2014
I have everything else working. My problem is that when i type "quit" to close the outer loop. It still runs the inner loop. The National Bank manager wants you to code a program that reads each clients charges to their Credit Card account and outputs the average charge per client and the overall average for the total number of clients in the Bank.
Hint: The OUTER LOOP in your program should allow the user the name of the client and end the program when the name entered is QUIT.In addition to the outer loop, you need AN INNER LOOP that will allow the user to input the clients charge to his/her account by entering one charge at a time and end inputting the charges whenever she/he enters -1 for a value. This INNER LOOP will performed the Add for all the charges entered for a client and count the number of charges entered.
After INNER LOOP ends, the program calculates an average for this student. The average is calculated by dividing the Total into the number of charges entered. The program prints the average charge for that client, adds the Total to a GrandTotal, assigns zero to the Total and counter variables before it loops back to get the grade for another client.Use DecimalFormat or NumberFormat to format the numeric output to dollar amounts.
The output of the program should something like this:
John Smith average $850.00
Maria Gonzalez average $90.67
Terry Lucas average $959.00
Mickey Mouse course average $6,050.89
National Bank client average $1,987.67
Code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = "";
int charge = 0;
int count = -1;
int total = 1;
int grandtotal = 0;
int average = 0;
[code]....
View Replies
View Related
Mar 8, 2014
How to convert this program from a while loop to a for loop.
import java.util.Scanner;
public class LongDivision {
public static void main(String arguments[]){
Scanner input = new Scanner(System.in);
System.out.println("Enter the dividend: ");
[Code] ....
View Replies
View Related
Feb 17, 2014
How do I convert my for loop below to a while and do while loop?
for(int a=1;a<=9;a++){
for(int b=1;b<=a;b++){
System.out.print(a);
}
System.out.println();
[Code] .....
View Replies
View Related
Feb 9, 2015
I am trying to make a program add values from a loop. So what its supposed to do is search through tokens on an imported file. The file lists State, Capital, and then capital population. Then take the population string, turn it into numbers, and then do stuff with the numbers. First I'm supposed to find the Highest and lowest population of the places in the file (which I did without problem), but the finally thing is I'm supposed to add each found population to the last so I can find the average of the populations.
I just cannot seem to grasp how to do that. I THINK I'm supposed to some how store the given value into a variable, but how do I get that variable to add to the new value?
like...?
Get token -> a
b = a
c = a + b
or wait no.....
Java Code :
import java.io.*;
import java.util.Scanner;
public class CapPopS
{
public static void main(String[] args) throws IOException
{
File stateCAP = new File("state-capital-2004population.txt");
if (!stateCAP.exists())
[Code] ....
View Replies
View Related
Feb 9, 2015
My teacher wants me to make a program that counts the amount of steps a student takes a day. The program asks for other info such as name, age, college. However I need to write a loop that will allow the user to enter how many ever steps they took and convert them to miles.how exactly to make the steps entered by the user within the loop be their own individual days like monday tuesday etc. Like the loop will ask how many steps did you take monday.. tuesday.. etc for each time it runs.
package StudentInfo;
import java.util.Scanner;
public class studentinfo {
public static void main (String [] args){
Scanner scan = new Scanner(System.in);
[code]....
View Replies
View Related
Apr 5, 2014
I need to write a program that measures how long it will take someone to make a million dollars if he is being paid $5.75 an hour, but the pay rate is increase by 0.2% each week after the third week.
View Replies
View Related
Feb 18, 2014
This is the first time I've ever gotten an infinite loop with a FOR loop. This program is supposed to let you enter five integer numbers and draw a bar chart based on those numbers. After the fifth number is entered, guess what? It wraps back around to zero again and starts over! Why the bleep doesn't it stop? The code is below:
Java Code: import java.awt.Graphics;
import javax.swing.JPanel;
import java.util.Scanner;
[Code]...
View Replies
View Related