Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Help with Iterators

  1. #1
    Junior Member
    Join Date
    Sep 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help with Iterators

    I am coding a puzzle checker to see if a certain solution that is given to me is a possible solution.

    I am at the beginning stages of coding but i have built a basic program. At the bottom of my code, I am getting this error.

    1 error found:
    File: C:\Users\xx\Desktop\Project 1 kenken\Kenken.java [line: 120]
    Error: variable temp might not have been initialized

    I am not sure how to initialize it.

    Here is the code.

    http://pastebin.com/ymW58qVZ

    Still learning about iterators. I have other classes i have not posted here and can explain if needed.
    Last edited by kivthur; September 26th, 2014 at 10:52 PM.


  2. #2
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Help with Iterators

     public KenkenIterator iterator()
      {
        KenkenIterator temp;
        return temp;
      }

    As it says, temp is never initialized. You could return self (since KenkenIterator implements Iterator)
     public KenkenIterator iterator()
      {
        return self;
      }

    Or you could make it a factory.
     public static KenkenIterator iterator()
      {
        KenkenIterator temp = new KenkenIterator();
        return temp;
      }


    Both are kind of pointless because KenkenIterator is-a Iterator
    Computers are fascinating machines, but they're mostly a reflection of the people using them.
    -- Jeff Atwood

  3. #3
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 697 Times in 679 Posts

    Default Re: Help with Iterators

    Welcome to the forum! Please read this topic to learn how to post code in code or highlight tags and other useful info for new members.

    Rather than providing a link to your code, please post it correctly using code or highlight tags per the above link.

  4. #4
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Help with Iterators

    Quote Originally Posted by ChristopherLowe View Post
     public KenkenIterator iterator()
      {
        KenkenIterator temp;
        return temp;
      }

    As it says, temp is never initialized. You could return self (since KenkenIterator implements Iterator)
     public KenkenIterator iterator()
      {
        return self;
      }
    Just wanted to point out that in Java the keyword is "this" and not "self". Some other languages use "self" instead, but it wont work in Java.

  5. The Following User Says Thank You to Cornix For This Useful Post:

    ChristopherLowe (September 27th, 2014)

  6. #5
    Junior Member
    Join Date
    Sep 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Iterators

    These were the instructions I was given, I am trying to follow them.

    "Start by writing the Cell class. Note that all of the other classes depend on it. Test your Cell class with a JUnitTestCase or by writing test code in a main method for your Cell class. Each Cell object will only contain information about its own value and will not contain any information about where it is located in the puzzle. For formatting, you can assume that all the cell values are a single digit.



    Then, write the Constraint class. It depends on the Cell class. Its constructor is passed the data for the three attributes for this instance of Constraint. The “value” is the expected result of executing the “operator” on the Cell values in the Constraint’s Cell []. In the constructor method, you need to use a “variable length parameter list” signature for the last parameter (the array of Cell references). Research and study how to use that feature of the Java language.



    Then, write the KenkenIterator class that implements Iterator as a private inner class in the Kenken.java file. Note that it needs to be written next because the Kenken and KenkenValidator classes depend on it. The KenkenIterator class has access to all the attributes of the Kenken class object that instantiates it. Its constructor method needs only to initialize the cursors needed by the hasNext method (to return true as long as there are still one dimensional arrays or constraints to be iterated) and the next method (to return the next one dimensional Cell array). Note that these methods must work correctly for any size Kenken puzzle. You must also implement a stub for a remove method even though we have no use for it in this application.



    Then, write the iterator method in the Kenken class. Only, the KenkenValidator class depends on this method. The Kenken class uses an underlying two dimensional array of Cell object references and a one dimensional array of Constraint objects as its primary data structures. The API for the Kenken class does not expose that internal data structure. The overloaded constructor for the Kenken class takes a Scanner object that was instantiated to read a file containing the dimension of the puzzle (size), the number of constraints, the constraint attributes, and the size2 digits of the proposed solution to be validated. The Kenken class implements Iterable<Cell[]>. Its iterator method must instantiate and return an object of KenkenIterator class.


    "

    Thank you for all the help so far, will test it out.

  7. #6
    Junior Member
    Join Date
    Sep 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Iterators

    This is my kenkenvalidator method and i am testing it. Everytime i run it, i get this error. "bad file name" even though i have the "puzzle01" file in my project folder.

    This is my code for the other classes.

    public class KenkenValidator
    {
      private Kenken puzzle;
     
      /**
       * @param args - not used
       */
      public static void main( String [] args)
      {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter name of filepuzzle01 containing puzzle to verify");   
        KenkenValidator myValidator = new KenkenValidator(scan.nextLine());
        System.out.println(myValidator.isSolution() ? 
                    "It is a valid solution" : "It is not a valid solution");
      }
     
      public KenkenValidator(String fileName)
      {
        Scanner file = null;
        try
        {
          file = new Scanner(new File(fileName));
        }
        catch (Exception e)
        {
          System.out.println("Bad file name");
          System.exit(0);
        }
     
        puzzle = new Kenken(file);
        System.out.println(puzzle);
      }
     
      public boolean isSolution()
      {
        return true;
        // code to iterate over the Cell arrays and check each one here
      }
    }

    public class Constraint extends Cell
    {
      public Constraint(int value, char op, Cell[]...cage)
      {
      }
     
      public boolean isValid()
      {
        return true; 
      }
    }

    public class Cell 
    {
      private int value; 
     
      public Cell()
      {
      }
     
      public void setValue(int v)
      {
        value = v;
      }
     
      public int getValue()
      {
        return value;
      }
     
      public String toString()
      {
        String temp = "hi";
        return temp;
      }
     
    }

    I feel like i am missing some fundamental things here as i keep running into problems. If any of you could get me on the right track, it would be greatly appreciated.

    Here is the main kenken class i have so far.

    import java.util.Scanner;
    import java.util.Iterator;
    import java.io.*;
     
    public class Kenken implements Iterable<Cell []>
    {
      private final int SIZE;
      private Cell [][] puzzle;
      private Constraint [] constraints;
     
      /** Puzzle File Format:
        * 
        * ASCII text file with following data in each line:
        * 4  8 // size and number of constraints
        * // constraints
        * 4 + 2 0 0 0 1
        * 2 / 2 0 2 0 3
        * 1 - 2 1 0 1 1
        * 3 - 2 1 2 1 3
        * 5 + 2 2 0 3 0
        * 6 * 2 2 1 2 2
        * 2 / 2 3 1 3 2
        * 2 - 2 2 3 3 3
        * // solution
        * 3 1 4 2
        * 2 3 1 4
        * 4 2 3 1
        * 1 4 2 3
        * 
        */
     
      public Kenken(Scanner file) 
      {
        // read puzzle to be solved from a file Scanner
        Scanner line = new Scanner(file.nextLine());    // get size - first token on line 1
        SIZE = line.nextInt();
        puzzle = new Cell [SIZE][SIZE];                 // setup puzzle based on the SIZE
          for (int i = 0; i < puzzle.length; i++)
            for (int j = 0; j < puzzle.length; j++)
              puzzle[i][j] = new Cell();
     
        constraints = new Constraint[line.nextInt()];   // get number of constraints - second token on line 1
        file.nextLine();                                // get rid of comment line in file format
     
        int index = 0;
        for (int i = 0; i < constraints.length; i++)    // process each constraint in the file
        {
          String s = file.nextLine();
          Scanner constraint = new Scanner(s);          // one constraint per line
          int value = constraint.nextInt();                  // the value
          char op = constraint.next().charAt(0);             // the operator
          if (op == 's')                                     // space substitution char is 's'
            op = ' ';
          int cells = constraint.nextInt();                  // the number of Cells in the cage
          Cell [] cage = new Cell[cells];
          for (int j = 0; j < cells; j++)  {                 // the pairs of ints for the Cell indices in puzzle
            int a = constraint.nextInt();
            int b = constraint.nextInt();
            cage[j] = puzzle[a][b];
          }
     
          constraints[index++] = new Constraint(value, op, cage);  // create the constraint from input data
        }
     
        // fill in puzzle array with solution to be tested
        file.nextLine();                                // get rid of comment line in file format
     
        for (int i = 0; i < puzzle.length; i++) {
          for (int j = 0; j < puzzle.length; j++) {
            puzzle[i][j].setValue(file.nextInt());
          }
        }
      }
     
      public String toString()
      {
        String s = "";
        for (int i = 0; i < puzzle.length; i++) 
          for (int j = 0; j < puzzle.length; j++)
            s += puzzle[i][j] + ((j != puzzle.length - 1) ? ", " : "\n");
        return s;
      }
     
      public class KenkenIterator implements Iterator<Cell []>
      {
       private Cell [][] puzzle;
       private int cursor; 
       private int cursorConstraint;
     
       public KenkenIterator()
       {
        cursor = cursorConstraint = 0;
       }
     
       public boolean hasNext()
       {
         return cursor < puzzle.length;
       }
     
       public Cell[] next()
       {
         Cell [] value = puzzle[cursor];
         cursor ++;
         return value;
       }
     
       public void remove()
       {
       }
      }
     
      public KenkenIterator iterator()
      {
        KenkenIterator temp = new KenkenIterator();
        return temp;
      }
    }

  8. #7
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Help with Iterators

    Expand this code out:
    file = new Scanner(new File(fileName));

    and stick in a println to check it really is looking in the right place for the file

    File file = new File( fileName );
    System.out.println( file.getAbsolutePath() );
    Scanner scanner = new Scanner( file );

    also, in the catch part of that try/catch stick in a message from the exception itself (to check it really is a FileNotFoundException):

    } catch (Exception e) {
     System.out.println("Bad file name");
     System.out.println(e.toString());
    }
    Computers are fascinating machines, but they're mostly a reflection of the people using them.
    -- Jeff Atwood

Similar Threads

  1. Nested Iterators
    By keepStriving in forum Java Theory & Questions
    Replies: 2
    Last Post: November 18th, 2013, 11:29 PM
  2. Iterators and lists and oh god my brain hurts!
    By Brodie337 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 8th, 2011, 04:44 PM
  3. iterators & linked lists in java question
    By somewhat_confused in forum What's Wrong With My Code?
    Replies: 1
    Last Post: June 4th, 2010, 10:59 AM