Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Infinite loop, can't find cause.
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Ethan3210




PostPosted: Wed Nov 03, 2010 7:25 pm   Post subject: Infinite loop, can't find cause.

I've been working on a project for my Grade 12 class, and I'm using a for loop, with String.charAt(x), and Thread.sleep, to cause a message to appear on the screen, one character at a time. However, the loop doesn't stop after the full message appears. Instead, it loops back to the start, and repeats infinitely. I'll post a short and long version of the code I'm using.

Short (in paint method, except for initialization of testword and total):
code:

String testword = "This sentence is not a test. Well, maybe it is. I don't know, really. But one thing's for sure. ";
String total[];
total = new String[3];
                total[0]="";
                total[1]="";
                total[2]="";

for (int x=0; x < testword.length(); x++){
                      total[i]+= testword.charAt(x);
                      y++;
                      comp2D.drawString(total[0],5,ydraw);       
                                comp2D.drawString(total[1],5,ydraw+15);
                                comp2D.drawString(total[2],5,ydraw+30);
                      if (y >=46){
                          i++;
                          y = 0;
                          }
                      if (i == 3){
                          i=0;
                          total[0] ="";
                          total[1] ="";
                          total[2] ="";
                      }
                      try {
                    Thread.sleep(50);
                                        }
                                catch (Exception ex) {
                                        }
                  }


Basically, the program prints the string 'total', which has one letter added onto it every 50ms. When 46 characters are on a line (since I can't figure out how to get the text to output on a new line when it reaches past a certain co-ordinate) it raises 'i' by one. This changes the reference to the next part of 'total', and continues to print out the sentence. After doing this three time, it changes 'i' to 0 again (for the next sentence which will appear after the user clicks).

Full code:
code:

import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Scanner;
import java.io.*;


public class PhoenixCase extends JFrame implements Runnable, MouseListener, MouseMotionListener{
        Thread runner;
        boolean lobbydefense, courtdefense,courtpros,courtwit,courtjudge;
        Image defenselobby, courtdbench, courtpbench, courtwbench, courtjbench, background;
        Toolkit kit = Toolkit.getDefaultToolkit();
        boolean intro = false;
        javax.swing.Timer ha;
        int indexerness=0, test = 0, ydraw=155, newline=53, i=0, y=0;
        String anythingrightnow[];
        String anythingrightnow2[];
        String total[];
        String testword = "This sentence is not a test. Well, maybe it is. I don't know, really. But one thing's for sure. ";

    public PhoenixCase() {
        super();
        setFocusable(true);
        setVisible(true);
        setSize(550,400);
        setResizable(false);
        addMouseMotionListener(this);
        addMouseListener(this);
        setVisible(true);
        setFocusable(true);
        indexerness=0;
        total = new String[3];
       
                total[0]="";
                total[1]="";
                total[2]="";
                runner = new Thread(this);
                runner.start();
    }
    public void paint(Graphics comp){
        Graphics2D comp2D = (Graphics2D) comp;
        background = kit.getImage("Game3Images/menubackground.gif");
        defenselobby = kit.getImage("Game3Images/Backgrounds/DefendantLobby.png");
        courtdbench = kit.getImage("Game3Images/Backgrounds/defensebench.png");
        courtpbench = kit.getImage("Game3Images/Backgrounds/probench.png");
        courtwbench = kit.getImage("Game3Images/Backgrounds/witnessstand.png");
        courtjbench = kit.getImage("Game3Images/Baxckgrounds/judgeseat.jpg");
        comp2D.drawImage(background,0,0,this);
        if (!intro){
            comp2D.setColor(Color.black);
            comp2D.fillRect(0,0,256,192);
            comp2D.setColor(Color.gray);
            comp2D.fillRect(1,140,255,52);
            comp2D.setColor(Color.blue);
            comp2D.fillRect(1,130,50,10);
            comp2D.setColor(Color.white);
            for (int x=0; x < testword.length(); x++){
                      total[i]+= testword.charAt(x);
                      y++;
                      comp2D.drawString(total[0],5,ydraw);       
                                comp2D.drawString(total[1],5,ydraw+15);
                                comp2D.drawString(total[2],5,ydraw+30);
                      if (y >=46){
                          i++;
                          y = 0;
                          }
                      if (i == 3){
                          i=0;
                          total[0] ="";
                          total[1] ="";
                          total[2] ="";
                      }
                      try {
                    Thread.sleep(50);
                                        }
                                catch (Exception ex) {
                                        }
                  }
                       
        }
        else comp2D.drawImage(defenselobby,0,0,this);
                repaint();
    }     
        public void mouseEntered (MouseEvent me){}
        public void mousePressed (MouseEvent me){}
        public void mouseReleased (MouseEvent me){}
        public void mouseExited (MouseEvent me){}
        public void mouseClicked (MouseEvent me){}
        public void mouseDragged (MouseEvent me){}
        public void mouseMoved (MouseEvent me){}

        public void run(){
    }
}


I know there's no main method.

What I need help figuring out is why x never becomes greater that the length of the string.
Sponsor
Sponsor
Sponsor
sponsor
Ethan3210




PostPosted: Wed Nov 03, 2010 9:28 pm   Post subject: Re: Infinite loop, can't find cause.

Found a way to get out of it, but it's not horribly efficient...
Basically, I just put a boolean statement wrapped around it, and it changes to false after it runs through once. But then the text instantly disappears. Sad


Nevermind, fixed it.
But the screen flashes alot... I tried to use setDoubleBuffered(true); , but it wouldn't work.
Barbarrosa




PostPosted: Sun Nov 14, 2010 6:32 pm   Post subject: Re: Infinite loop, can't find cause.

The flashing probably happens because two threads are trying to access the same String at the same time. I had the same problem making my Memory Simulator (posted in the Java Submissions). You should probably make sure the threads don't do that.

I suggest that the UI thread use a StringBuilder that the non-UI thread synchronizes on and appends to.

Java:

StringBuilder strLabel;
String strAll;
...
CharacterIterator cit = new StringCharacterIterator(strAll);
for(cit.next() != CharacterIterator.DONE){
   synchronized(strLabel){
      strLabel.append(cit.current());
   }
   Thread.sleep(50);
}
...
//in UI thread
comp2D.drawString(strLabel.toString(),1,2);


Edit:

If you want to go a bit further, you could have another thread that allocates and updates a String for the UI thread if (and only if) the StringBuilder's contents have changed, waiting until it's finished with the allocation to synchronize on UI's String reference. That could save the UI thread the work of converting the StringBuilder to a String.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 3 Posts ]
Jump to:   


Style:  
Search: