Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-09-2012, 08:06 PM   PM User | #1
carlisle
New to the CF scene

 
Join Date: Jan 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
carlisle is an unknown quantity at this point
Newbie help with "while" statements.

Hello! I'm new to the world of programming and after a few weeks in my Java class have run into some homework trouble. We've been working the the Java Au Naturel book and the current assignment is to:

"Revise the lastEmptySlot method to return the position of the next to- last empty slot. Return the initial position if the executor has less than two empty slots."

I put together something I thought would work, but somewhere I think the "while" statements are messing it up.
Any help would be much appreciated.

Thanks.



PHP Code:
public String lastEmptySlot()
     {    
int count 0;
    
String spot this.getPosition();
    
String lastEmpty spot;  // in case no later slot is empty
         
    
while (this.seesSlot())
          {   if (!
this.seesCD())
            
count++;// count number of empty slots
           
moveOn();
          }
        if (
count 2)
        return 
lastEmpty;
        else {
        
this.backUp();
          while (
this.seesSlot())
          {    if ( ! 
this.seesCD()){
                    
lastEmpty this.getPosition();
              break;
             }
               
this.backUp();
          }
          while (
this.seesSlot()){
            if ( ! 
this.seesCD()){
                     
lastEmpty this.getPosition();
               break;
            }
            
this.backUp();
        }
          return 
lastEmpty;
        }
     }    
//======================= 
Also, we use a "Vic" class for setting up all the scenarios in the book (in this case CDs).

PHP Code:
// <pre>
// Copy this file in its entirety to a file named Vic.java
// Compile it before trying to compile any program that uses it
// This implementation uses ArrayLists for the sequences of CDs
// It also uses an initializer method to create the tableau before any Vics

import java.util.*;
import java.awt.*;
import javax.swing.*;

public class 
Vic
{
    private static 
Stack theStack = new Stack();  // where spare CDs are kept
    
private ArrayList itsSequence;  // its slots
    
private int itsPos;             // 0,1,2,...; 0 is at front
    
private int itsID;              // 1 for first Vic, 2 for...

    /* QUERY METHODS */
    /** Return the current position as a String value.  */
    
public String getPosition()
    {    return 
itsID ", " itsPos;
    }    
//======================

    /** Tell whether there is a slot at its position.  */
    
public boolean seesSlot()
    {    return 
itsPos itsSequence.size();
    }    
//======================

    /** Tell whether there is a CD in its current slot.  */
    
public boolean seesCD()
    {    if (! 
seesSlot())
            
fail ("Can't see a CD where there is no slot!");
        return 
itsSequence.get (itsPos) != null;
    }    
//======================

    /** Return the CD that is in its current slot.  */
    
public String getCD()
    {    if (! 
seesSlot())
            
fail ("There is no slot to get a CD from!");
        return (String) 
itsSequence.get (itsPos);
    }    
//======================

    /** Tell whether the stack has any CDs available. */
    
public static boolean stackHasCD()
    {    return ! 
theStack.isEmpty();
    }    
//======================

    /* ACTION METHODS */
    /** Move forward to the next slot in the sequence. */
    
public void moveOn()
    {    if (! 
seesSlot())
            
fail ("Already at the end of the sequence!");
        
itsPos++;
        
trace ("moveOn to slot " + (itsPos 1));
    }    
//======================

    /** Back up to the previous slot in the sequence. */
    
public void backUp()
    {    if (
itsPos == 0)
            
fail ("Already at the front of the sequence!");
        
itsPos--;
        
trace ("backUp to slot " + (itsPos 1));
    }    
//======================

    /** Move a CD from the stack to the current slot.  */
    
public void putCD()
    {    if (! 
seesCD() && stackHasCD())
            
itsSequence.set (itsPostheStack.pop());
        
trace ("putCD at slot " + (itsPos 1));
    }    
//======================

    /** Move a CD from the current slot to the stack.  */
    
public void takeCD()
    {    if (
seesCD())
        {    
theStack.push (itsSequence.get (itsPos));
            
itsSequence.set (itsPosnull);
        }
        
trace ("takeCD at slot " + (itsPos 1));
    }    
//======================

    /** Terminate the program with an appropriate message.  */
    
private void fail (String cause)
    {    
JOptionPane.showMessageDialog (null"STOPPING: " cause
            
"  (Vic #)" itsID ", position =" itsPos);
        
System.exit (0);
    }    
//======================

    /** Two convenience methods */
    
public void shiftFromSlotToStack()
    {    
takeCD();
    }    
//======================

    
public void shiftFromStackToSlot()
    {    
putCD();
    }    
//======================
    
     /** Back up to the string position */

      
public void backUpTo (String someSpot)
     {  while (! 
someSpot.equals (getPosition()))
            
backUp();
     } 

    
/* METHODS THAT USE THE FRAME */
    
private static String vicSay "Programmable CD Organizer "
        
"        mfd by Jones & Co.";
    private static final 
VicFrame theFrame = new VicFrame();
    
//////////////////////////////////

    
public static void say (String message)
    {    
vicSay message;
        
theFrame.repaint();
    }    
//======================

    /** Print a trace of the Vic's action.  */
    
private void trace (String message)
    {    
System.out.println (message " for Vic #" itsID);
        
theFrame.repaint();
        
pause (500);  // half-a-second between actions
    
}    //======================

    /** Pause for the specified number of milliseconds.  */
    
private static void pause (int milliseconds)
    {    try
        {    
Thread.sleep (milliseconds);
        }
        catch (
InterruptedException e)
        {    
// never happens
        
}
    }    
//======================

    /* THE INITIALIZER AND CONSTRUCTOR METHODS */
    
private static final int MAXSLOTS 8;
    private static final 
int MINSLOTS 3;
    private static final 
int MAXVICS  4;
    private static final 
Random random = new Random();
    private static 
int theMaxVics random.nextInt (MAXVICS) + 1;
    private static 
ArrayList[] theSeq = new ArrayList[theMaxVics];
    private static 
int theNumVics 0;
    private static final 
Vic[] theVics = {nullnullnullnull};
    
//////////////////////////////////

    /** Initialize individual sequences and stacks.  An initializer method
    is used because these have to exist before any Vics are created. */

    
static
    {    for (
int k 0;  theMaxVics;  k++)
        {    
theSeq[k] = new ArrayList();
            
int numSlots random.nextInt (MAXSLOTS MINSLOTS 1)
                + 
MINSLOTS;
            for (
int i 0;  numSlots;  i++)
            {    
String it random.nextInt (2) == 0  ?  null 
                    
"" + (char) ('a') + (1);
                
theSeq[k].add (it);
            }
        }

        
//add this code at line 150
        
for (int i 010i++)
        {
            
theStack.push ("CD#" i);// pushes 10 CDs to stack
        
}

//         // start with up to 2 CDs on the stack
//         if (random.nextInt (3) > 0)  // 2 times out of 3
//         {  theStack.push ("GarthB");
//             if (random.nextInt (2) == 0) // 1 time out of 3
//                 theStack.push ("LyleL");
//         }
    
}    //======================

    /** Construct a new Vic. */
    
public Vic()
    {    
super();
        
itsSequence =  theNumVics theMaxVics
        
?   theSeq[theNumVics]   :  new ArrayList();
        
itsPos 0;
        
itsID theNumVics 1;
        
theVics[theNumVics] = this;
        
theNumVics++;
        
trace ("construction");
    }    
//======================

    /** Replace random arrangement by user-specified arrangement. */
    
public static void reset (String[] args)
    {    if (
args.length && theNumVics == 0)
        {    
theMaxVics Math.min (args.lengthMAXVICS);
            
theSeq = new ArrayList[theMaxVics];
            for (
int k 0theMaxVics;  k++)
            {    
theSeq[k] = new ArrayList();
                
int longest Math.min (args[k].length(), MAXSLOTS);
                for (
int i 0;  longest;  i++)
                {    
String it args[k].charAt (i) == '0' null 
                        
"" + (char)('a') + (1);
                    
theSeq[k].add (it);
                }
            }
        }
    }    
//======================

    // THE NESTED FRAME CLASS
    
static class VicFrame extends JFrame
    
{    private final int SLOT 75;           // between CD slots
        
private final int EDGE 10;           // leave free at left side
        
private final int WIDTH = (MAXSLOTS 2) * SLOT EDGE;
        private final 
int DIST 60;           // between CD sequences
        
private final int SAY 45;            // depth of say's output
        
private final int TOPSEQ SAY DIST// depth of first seq

        
public VicFrame()
        {    
addWindowListener (new Closer());
            
setSize (WIDTHTOPSEQ MAXVICS DIST EDGE);
            
setBackground (new Color (255252224)); // a nice cream
            
setVisible (true);    // make it visible to user
        
}    //======================

        /** Same as for an applet; called by repaint. */
        
public void paint (Graphics page)  
        {    
// PRINT THE vicSay MESSAGE AT THE TOP
            
page.setColor (getBackground());
            
page.fillRect (EDGEEDGEWIDTH EDGE
                
TOPSEQ MAXVICS DIST);
            
page.setColor (Color.white);
            
page.fillRect (20SAY 20WIDTH 4020);
            
page.setColor (new Color (0960));  // a light green
            
page.drawString (vicSay25SAY 5); // message

            // DRAW UP TO FOUR Vic SEQUENCES AND THE STACK
            
for (int k 0;  theMaxVics;  k++)
                
drawSequence (pagekTOPSEQ DIST);
            
page.setColor (Color.red);
            
int y TOPSEQ MAXVICS DIST;
            
page.drawString ("stack"EDGEy);
            
page.fillRect (EDGE25405);  // dividing line
            
for (int k 0;  theStack.size();  k++)
                
page.drawString ((String) theStack.get (k),
                    
EDGE30 20);
        }    
//======================

        /** Called by VicFrame's paint method. */
        
private void drawSequence (Graphics pageint indexint y)
        {    
page.setColor (Color.red);
            if (
theVics[index] != null)
                
drawMacMan (pagetheVics[index].itsPos15);
            
page.setColor (Color.blue);
            
drawAllCDs (pageytheSeq[index]); 
        }    
//======================

        
private void drawAllCDs (Graphics pageint y,
        
ArrayList slots)
        {    
int atEnd slots.size();
            for (
int n 0;  atEnd;  n++)
            {    
String it = (String) slots.get (n);
                
page.drawString (it == null "---" it
                    (
1) * SLOT EDGEy);
            }
            
page.drawString ("END", (atEnd 1) * SLOT EDGEy);
        }    
//======================

        
private void drawMacMan (Graphics pageint posint y)
        {    
// <x, y> is the lower-left corner of the stick figure
            
int x pos SLOT EDGE 78;
            
page.setColor (Color.black);
            
page.drawLine (x,     y,      6,  6);  // leg
            
page.drawLine (66,  12y);      // leg
            
page.drawLine (66,  6,  18); // body
            
page.drawLine (x,     141214); // arms
            
page.drawOval (12810,     10);     // head
            
page.drawLine (4255,  25); // eye
            
page.drawLine (7258,  25); // eye
            
page.drawLine (3229,  22); // mouth
        
}    //======================
    
// end of VicFrame class

    
private static class Closer extends java.awt.event.WindowAdapter 
    
{    
        public 
void windowClosing (java.awt.event.WindowEvent e
        {    
System.exit (0);
        }    
//======================
    
}     
}     

// </pre> 

Last edited by carlisle; 01-09-2012 at 08:26 PM.. Reason: Added Vic to see if that would help.
carlisle is offline   Reply With Quote
Old 01-09-2012, 09:00 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Assuming that you cannot go from the end to the start, you can shadow the variable instead to limit the work (the datastorage you are using would let you do this, but you don't have a way to access the end from your method). There is no reason to iterate more than once (if I perceive this list properly).

PHP Code:
public String lastEmptySlot() 
{
    
String spot this.getPosition();
    
String lastEmpty null;
    
String shadow null;
    
int iEmpty 0;
    while (
this.seesSlot())
    {
        if (!
this.seesCD()) // nothing there
        
{
            
shadow lastEmpty;
            
lastEmpty this.getPosition();
            ++
iEmpty;
        }
        
this.moveOn();
    }  
    if (
shadow == null || iEmpty 2)
    {
        
shadow spot;
    }
    return 
shadow;

Its slightly easier execution wise if you can seek to the end. If that can be done, you can iterate backwards and break the loop or add an additional check once 3 empty slots have been found.

Try that out. Works alright in my head.
Fou-Lu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 12:28 PM.


Advertisement
Log in to turn off these ads.