Solved

How can I print my list up to max value identified in input???

Posted on 2007-11-25
24
197 Views
Last Modified: 2010-03-30
     max = getInt("   It should be an integer value greater than or equal to 2.");
        ListInterface candidateList = new AList();
        candidateList.add(2);
        candidateList.add(3);
        candidateList.add(4);
        candidateList.add(5);
        candidateList.add(6);
        candidateList.add(7);
        candidateList.add(11);
        candidateList.add(13);
        candidateList.add(17);                
       System.out.println("Candidate List:   ");
       System.out.printf(candidateList.max(candidateList));

my output should be 2,3,5,7

That is saying user input listed 7.

If user listed 5, output should be 2,3,5

if user listed 11, output should be 2,3,4,5,6,7,11
0
Comment
Question by:ahowe01
  • 8
  • 7
  • 5
  • +1
24 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 20346961
Given user input n, you simply need to iterate your primes list such that all <= n are printed out
0
 

Author Comment

by:ahowe01
ID: 20347084
hi again..

so why is this not working???  I even left your code the same... (from my previous question) thinking I could alter it to match my syntex throughout the remaining of my program after I get it to compile.  But I cannot get past the error.  

cannot find symbol method listIterator()

??

I hope you are not annoyed with my questions.  

import java.util.ListIterator;

import java.io.*;

import java.util.*;
 
 

public class Primes {
 

    public static void main( String args[] )   

     {
 

        int max;        

        System.out.println( "Please enter the maximum value to test for primality" );

        max = getInt("   It should be an integer value greater than or equal to 2.");

        

       // Creates Prime List 	

       ListInterface primeList = new AList();

       

       //  Creates Composites List

       ListInterface compositesList = new AList();      

 

       // Creates Candidate List 

        ListInterface candidateList = new AList();

        candidateList.add(2);

        candidateList.add(3);

        candidateList.add(4);

        candidateList.add(5);

        candidateList.add(6);

        candidateList.add(7);

        candidateList.add(11);

        candidateList.add(13);

        candidateList.add(17);    

        	

             

  //     System.out.println("Candidate List:   ");

  //     System.out.print(max);  

       	

        int ix = 0;

        int upperLimit = max;

        ListIterator i = primeList.listIterator();

        while (i.hasNext() && ix++ < upperLimit) {

        i.next();

        i.remove();

}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20347104
If the method is not recognised, it mean that your ListInterface does not implement java.util.List. You will have to iterate it in some other way. please post definition of ListInterface
0
 
LVL 17

Expert Comment

by:contactkarthi
ID: 20347116
for n= 0 to length of the list - 1
get the val of the nth position from the list
compare the value to the input
if it is greater brek the loop
iterate the loop

use the help from the samples in the below link and implement the above algorithm
http://www.faqs.org/docs/javap/c12/ex-12-4-answer.html
0
 
LVL 17

Expert Comment

by:contactkarthi
ID: 20347123
ix++ < upperLimit in the while loop will iterate the loop that many times and not till the max value

say if you give max value as 7 the loop will iterate 7 times
0
 

Author Comment

by:ahowe01
ID: 20347156
here is my listInterface.....

public interface ListInterface<T>

{	

/** Task: Adds a new entry to the end of the list.

Entries currently in the list are unaffected.

The list’s size is increased by 1.

* @param newEntry the object to be added as a new entry

* @return true if the addition is successful, or false if the list

is full */
 

public boolean add(T newEntry);
 
 

/** Task: Adds a new entry at a specified position within the list.

* Entries originally at and above the specified position

* are at the next higher position within the list.

* The list’s size is increased by 1.

* @param newPosition an integer that specifies the desired

* position of the new entry

* @param newEntry the object to be added as a new entry

* @return true if the addition is successful, or

* false if either the list is full, newPosition < 1, or

* newPosition > getLength()+1 */

public boolean add(int newPosition, T newEntry);
 
 

/** Task: Removes the entry at a given position from the list.

* Entries originally at positions higher than the given

* position are at the next lower position within the list,

* and the list’s size is decreased by 1.

* @param givenPosition an integer that indicates the position of

* the entry to be removed

* @return a reference to the removed entry or null, if either

* the list was empty, givenPosition < 1, or

* givenPosition > getLength() */

public T remove(int givenPosition);
 
 

/** Task: Removes all entries from the list. */

public void clear();
 
 

/** Task: Replaces the entry at a given position in the list.

* @param givenPosition an integer that indicates the position of the

* entry to be replaced

* @param newEntry the object that will replace the entry at the

* position givenPosition

* @return true if the replacement occurs, or false if either the

* list is empty, givenPosition < 1, or

* givenPosition > getLength() */

public boolean replace(int givenPosition, T newEntry);
 
 

/** Task: Retrieves the entry at a given position in the list.

* @param givenPosition an integer that indicates the position of

* the desired entry

* @return a reference to the indicated entry or null, if either

* the list is empty, givenPosition < 1, or

* givenPosition > getLength() */

public T getEntry(int givenPosition);
 
 

/** Task: Sees whether the list contains a given entry.

* @param anEntry the object that is the desired entry

* @return true if the list contains anEntry, or false if not */

public boolean contains(T anEntry);
 
 

/** Task: Gets the length of the list.

* @return the integer number of entries currently in the list */

public int getLength();
 
 

/** Task: Sees whether the list is empty.

* @return true if the list is empty, or false if not */

public boolean isEmpty();
 
 

/** Task: Sees whether the list is full.

* @return true if the list is full, or false if not */

public boolean isFull();
 
 

/** Task: Displays all entries that are in the list, one per line,

* in the order in which they occur in the list. */

public void display();
 

} // end ListInterface

Open in new window

0
 
LVL 92

Expert Comment

by:objects
ID: 20347173
try:

        ListIterator i = primeList.listIterator();
        while (i.hasNext()) {
           int next = i.next();
           if (next>upperLimit) i.remove();
        }
        System.out.println(primeList);
0
 
LVL 17

Expert Comment

by:contactkarthi
ID: 20347182
ListIterator i = primeList.listIterator();
        while (i.hasNext() && ix++ < upperLimit) {
        i.next();
        i.remove();
}

should be written something like

 ListIterator i = primeList.listIterator();
        while (i.hasNext()) {
        i.next();
        // get the value and check if it greater and break the list
if(val > upperLimeit) break;

        i.remove();
}
0
 
LVL 17

Expert Comment

by:contactkarthi
ID: 20347192
misinterpreted the question

it should be remove not break
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 200 total points
ID: 20347222
Iterate using method getEntry in a loop
0
 

Author Comment

by:ahowe01
ID: 20347236

listIterator errors out... is says,   cannot find symbol method listIterator()

here is the list that implements the listInterface
class AList<T> implements ListInterface<T> 

{

  private T[] list; // array of list entries

  private int length; // current number of entries in list

  private static final int MAX_SIZE = 50; // max length of list
 

  public AList() {

    this(MAX_SIZE);  // call next constructor

  } // end default constructor
 

  public AList(int maxSize) {

    length = 0;

    list =  (T[]) new Object[maxSize];

  } // end constructor
 

  public boolean add(T newEntry) {

    boolean isSuccessful = true;

    if (!isFull()) {

      // Assertion: Length of list < length of array

      assert length < list.length;

      

      // position of new entry will be after last entry in list,

      // that is, at position length+1; corresponding array index is

      // 1 less than position, so index is length

      list[length] = newEntry;

      length++;

    }

    else

      isSuccessful = false;
 

    return isSuccessful;

  } // end add
 

  public boolean add(int newPosition, T newEntry) {

    boolean isSuccessful = true;
 

    if (!isFull() && (newPosition >= 1) && (newPosition <= length+1)) {

      makeRoom(newPosition);

      list[newPosition-1] = newEntry;

      length++;

    }

    else

      isSuccessful = false;
 

    return isSuccessful;

  } // end add
 

  public T remove(int givenPosition) {

    T result = null; // return value
 

    if ((givenPosition >= 1) && (givenPosition <= length)) 

    {

      assert !isEmpty();

      result = list[givenPosition-1]; // get entry to be removed

      // move subsequent entries toward entry to be removed,

      // unless it is last in list

      if (givenPosition < length)

        removeGap(givenPosition);

      length--;

    }
 

    return result;

  } // end remove
 

  public void clear() {

    length = 0;

  } // end clear
 

  public boolean replace(int givenPosition, T newEntry) {

    boolean isSuccessful = true;
 

    if ((givenPosition >= 1) && (givenPosition <= length))

    {

      assert !isEmpty();

      list[givenPosition-1] = newEntry;

    }

    else

      isSuccessful = false;
 

    return isSuccessful;

  } // end replace
 

  public T getEntry(int givenPosition) {

    T result = null; // result to return
 

    if ((givenPosition >= 1) && (givenPosition <= length))

    {

      assert !isEmpty();

      result = list[givenPosition-1];

    } // end if
 

    return result;
 

  } // end getEntry
 

  public boolean contains(T anEntry) {

    boolean found = false;
 

    for (int index = 0; !found && (index < length); index++) 

    {

      if (anEntry.equals(list[index]))

        found = true;

    } // end for
 

    return found;

  } // end contains
 

  public int getLength() {

    return length;

  } // end getLength
 

  public boolean isEmpty() {

    return length == 0;

  } // end isEmpty
 

	  public boolean isFull() {

    return length == list.length;

  } // end isFull
 

  public void display() {

    for (int index = 0; index < length; index++)

      System.out.println(list[index]);

  } // end display
 

  

  public boolean equals(AList<T> aList) {

    boolean result=true; // result of comparison of lists

    int     position;  // want position available throughout method
 

   

    if (length == (aList.getLength())) {

      // lists have equal lengths, so traverse both and compare items as you go:

      for (position = 0; (position < length) && list[position].equals(aList.list[position]);

                                                                                  position++)

      {

      }  // end for
 

      // if lists are equal, position will equal numElements in previous loop

      result = position == length;

    }

    else  // lists have unequal lengths

      result = false;
 

    return result;

  }  // end equals
 

  
 

  

  

   /** Task: Makes room for a new entry at newPosition.

    * Precondition: 1 <= newPosition <= length+1;

    * length is list’s length before addition. */

   private void makeRoom(int newPosition)

   {

       assert (newPosition >= 1) && (newPosition <= length + 1);

       int newIndex = newPosition - 1;

       int lastIndex = length - 1;

       // move each entry to next higher index, starting at end of

       // array and continuing until the entry at newIndex is moved

       for (int index = lastIndex; index >= newIndex; index--)

            list[index + 1] = list[index];

       } // end makeRoom

       

  /** Task: Shifts entries that are beyond the entry to be removed

  * to next lower position.

  * Precondition: 1 <= givenPosition <= length;

  * length is list’s length before removal. */

  private void removeGap(int givenPosition) 

  {   assert (givenPosition >=1) && (givenPosition < length);

    

    int removedIndex = givenPosition - 1;

    int lastIndex = length - 1;

    for (int index = removedIndex; index < lastIndex; index++)

      list[index] = list[index + 1];

  } // end removeGap
 

  

      /** Task: Give a string representation of the list

     *

     * @return a string showing the state of the list

     */

    public String toString()

    {

        String result = "{ ";

        for(int i=0; i<length; i++)

        {

            result = result + "<" + list[i] + "> ";

        }

        result = result + "}";

        

        return result;

    }

}

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20347251
See my last comment
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 17

Expert Comment

by:contactkarthi
ID: 20347260
if you want to just print the list use the following

 ListIterator i = primeList.listIterator();
        while (i.hasNext()) {
val = i.getEntry(ix++);
if(val > upperLimeit) break;
System.out.println(val);
        i.next();
}

if you want to remove values

 ListIterator i = primeList.listIterator();
        while (i.hasNext()) {
val = i.getEntry(ix++);
if(val > upperLimeit) i.remove();
        i.next();
}
0
 
LVL 92

Assisted Solution

by:objects
objects earned 150 total points
ID: 20347269
try this:

for (int i=primeList.getLength(); i>=0; i--)
{
   int value = primeList.getEntry(i);
   if (value>upperLimit)
   {
       primtList.remove(i);
   }
}
0
 

Author Comment

by:ahowe01
ID: 20347270
ok... Let me see.  getting out my notes for guidance.  I'm so not good at java....
0
 
LVL 92

Expert Comment

by:objects
ID: 20347275
Implementing an Iterator and using the code I posted earlier would be a more flexible solution though. Up to which best meets your needs, both will work.

Let me know if you have any questions.
0
 

Author Comment

by:ahowe01
ID: 20347419

Ok... now what am I doing wrong?

    //  System.out.print(max);    
   for (int position = candidateList.getLength(); position>=0; position--)
   {
        Integer index = (Integer)candidateList.getEntry(position);
        if (index > max)
      {
       candidateList.remove(position);
      }
      System.out.print(candidateList);
   }

Please enter the maximum value to test for primality
   It should be an integer value greater than or equal to 2.
7

HERE IS MY OUTPUT.....
{ <2> <3> <4> <5> <6> <7> <11> <13> }{ <2> <3> <4> <5> <6> <7> <11> }{ <2> <3> <4> <5> <6> <7> }{ <2> <3> <4> <5> <6> <7> }{ <2> <3> <4> <5> <6> <7> }{ <2> <3> <4> <5> <6> <7> }{ <2> <3> <4> <5> <6> <7> }{ <2> <3> <4> <5> <6> <7> }{ <2> <3> <4> <5> <6> <7> }Exception in thread "main" java.lang.NullPointerException
    at Primes.main(Primes.java:38)
0
 
LVL 17

Assisted Solution

by:contactkarthi
contactkarthi earned 150 total points
ID: 20347442
if (index > max)
      {
       candidateList.remove(position);
      }
else
{
break;
}

0
 
LVL 92

Expert Comment

by:objects
ID: 20347445
you accessing a var whose value is null at line 38
0
 
LVL 17

Expert Comment

by:contactkarthi
ID: 20347456
or try this

for (int position = candidateList.getLength(); position>0; position--)
0
 

Author Comment

by:ahowe01
ID: 20347560
thank you everyone.   This question is answered....  I'll be back with another question I'm sure.   Have several objectives trying to meet.   Most of all, I want to learn this language!!

Do have a question before I depart.  

What makes the list display different?

Where my output is.....
{ <2> <3> <4> <5> <6> <7> <11> <13> }  //this I've never seen until I error'ed out, as my comment listed earlier.

or my output is....
2
3
4
5
6
7
11
 13
0
 
LVL 17

Expert Comment

by:contactkarthi
ID: 20347582
System.out.println of the list will give output like

{ <2> <3> <4> <5> <6> <7> <11> <13> }

if you want one number per line and nor brackets and < or > signs

iterate and print it

 ListIterator i = primeList.listIterator();
        while (i.hasNext()) {
System.out.println(i.getEntry(ix++));

}
0
 

Author Comment

by:ahowe01
ID: 20347747
Thank you so much!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20348830
:-)
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Entering a date in Microsoft Access can be tricky. A typo can cause month and day to be shuffled, entering the day only causes an error, as does entering, say, day 31 in June. This article shows how an inputmask supported by code can help the user a…
This is about my first experience with programming Arduino.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now