RainFall Problem

Ok I am somewhat done with this code. Just some little editing. This is the problem.
Write a program that reads in the average monthly rainfall for a city for each month of the year and then reads in the actual monthly rainfall for each of the previous 12 months. The program then prints out a nicely formatted table showing the rainfall for each of the previous 12 months as well as how much above or below average the rainfall was for each month. The average monthly rainfall is given for the months January, February, and so forth. To obtain the actual rainfall for the previous 12 months, the program first asks what the current month is and then asks for the rainfall figures for the previous 12 months. The month input can be handled in any manner you wish as long as it is relatively easy for the user. Include a loop that allows the user to repeat this entire calculation until the user requests that the program end.
Ok well here is my code:public class MonthandAverage {
     private String month;
     public void setMonth(int n){
          if(n==1){
               month="January";}
          else if(n==2){
               month="February";}
          else if(n==3){
               month="March";}
          else if(n==4){
               month="April";}
          else if(n==5){
               month="May";}
          else if(n==6){
               month="June";}
          else if(n==7){
               month="July";}
          else if(n==8){
               month="August";}
          else if(n==9){
               month="September";}
          else if(n==10){
               month="October";}
          else if(n==11){
               month="November";}
          else if(n==12){
               month="December";}
     public String getMonth()
          return month;
import java.io.*;
public class AverageRainfall {
static private InputStreamReader in = new InputStreamReader(System.in);
static private BufferedReader br = new BufferedReader(in);
public static void main(String[] Args)throws IOException
     MonthandAverage date =new MonthandAverage();
     System.out.println("National Weather Service");
     System.out.println("Please enter the current month number please.");
     System.out.println("For example, 7 for July");
     String inch = br.readLine();
     int n = Integer.parseInt(inch);
     date.setMonth(n);
     System.out.println("The current month is "+date.getMonth());
     System.out.println("Please enter in the rainfall amount for the past 12 months.");
     for(int i=1;i<=12;i++)
          String str = br.readLine();
          int rainfall = Integer.parseInt(str);
          date.setMonth(i);
          System.out.println("Month "+i+" is "+date.getMonth()+" and the rainfall is "+rainfall+" inches.");
          int count =0;
          count += rainfall;
          int average = count/12;     
          System.out.println("The average rainfall for each month is: "+average);
}First thing is that I need to have the program terminate at the users request. Would I just use an if statement and break if true?

Ok I am somewhat done. I am having difficulty trying to figure the way I should have the entering in of rainfall amounts start from the current month entered. Does anyone have an idea as to how I can approach this? Thanks.
import java.io.*;
public class AverageRainfall {
static private InputStreamReader in = new InputStreamReader(System.in);
static private BufferedReader br = new BufferedReader(in);
public static void main(String[] Args)throws IOException
     MonthandAverage date = new MonthandAverage();
     System.out.println("National Weather Service");
     System.out.println("Please enter the current month number.");
     System.out.println("For example, 7 for July");
     String mon = br.readLine();
     int month = Integer.parseInt(mon);
     date.setMonth(month);
     System.out.println("The current month is "+date.getMonth());
     System.out.println("Please enter in the average monthly rainfall for a city for the past 12 months: ");
     for(int i=1;i<=12;i++)
          String str = br.readLine();
          int rainfall = Integer.parseInt(str);
          date.setMonth(i);
          System.out.println("Month "+i+" is "+date.getMonth()+" and the average rainfall is "+rainfall+" inches.");
}OUTPUT:
National Weather Service
Please enter the current month number.
For example, 7 for July
7
The current month is July
Please enter in the average monthly rainfall for a city for the past 12 months:
2
Month 1 is January and the average rainfall is 2 inches.
3
Month 2 is February and the average rainfall is 3 inches.
5
Month 3 is March and the average rainfall is 5 inches.
6
Month 4 is April and the average rainfall is 6 inches.
4
Month 5 is May and the average rainfall is 4 inches.
2
Month 6 is June and the average rainfall is 2 inches.
8
Month 7 is July and the average rainfall is 8 inches.
5
Month 8 is August and the average rainfall is 5 inches.
9
Month 9 is September and the average rainfall is 9 inches.
4
Month 10 is October and the average rainfall is 4 inches.
4
Month 11 is November and the average rainfall is 4 inches.
8
Month 12 is December and the average rainfall is 8 inches.

Similar Messages

  • Problem with Div and table

    I have a table that contains data parsed for a weather station page.  It also has a webcam picture on the page.  Up until now, the webcam pic has loaded via an applet but I want to change that to a jquery slideshow so it's accessible to more mobile devices.   My problem is that no matter what I do (aside from putting a 5x240 spacer) I can't get the table data to display below the webcam div (id="featured").  I've put the webcam and data table in their own div, the webcam's div in the table, used clear:both on the divs, tried setting block size, but it's like nothing is working.   So I'm back to go and thought I'd post it here since there are so many folks here who know more about this than me.  This is the html, right now with no CSS classes or anything added.  So whatever you would suggest as far as div and/or table layout and any CSS would be appreciated.
    <table width="100%" cellpadding="3">
    <tr align="center"><td >
          <div id="featured"> <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img0" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-9.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img10" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-8.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img9" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-7.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img8" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-6.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img7" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-5.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img6" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-4.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img5" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-3.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img4" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-2.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img3" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-1.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img2" /></a>
                  <a href="http://www.spyglasshill.com/Webcam/" target="_new"><img src="http://spyglasshill.com/Webcam/netcam-0.jpg" alt="Webcam of Holland Channel from Spyglass Condos" width="320" height="253" border="0" id="Img1" /></a>  <!--end div featured--></div>
    </td></tr>
    <tr>
      <td><img src="images/spacer5x260.gif" width="5" height="260"></td></tr>
    <tr>
                          <td colspan="4"><p align="center"><a href="images/06/Waterspout/Waterspouts.htm"><br />
                              </a></p>
                            <div align="center">
                              <p><a href="images/Waterspout/Waterspouts.php">Waterspout on Lake Mich </a>||| <a href="images/ANIFreighter.gif">Freighter Leaving Harbor</a><br />
                              </p>
                            </div></td>
                          </tr>
                        <tr>
                          <td colspan="4" bgcolor="#EAEFF9"><div align="center">
                            <h2>Weather Conditions Last Updated  wvcurudwv at wvcurutwv </h2>
                          </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        Temperature                      </div></td>
                          <td><div align="left">                        wvcur01wv                      </div></td>
                          <td><div align="right">                        Wind Speed                      </div></td>
                          <td><div align="left">                        wvcur18wv                      </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        Average High                      </div></td>
                          <td><div align="left">                        wvahtempwv                      </div></td>
                          <td><div align="right">                        Wind Direction                      </div></td>
                          <td><div align="left">                        wvcur17wv                      </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        Record High                      </div></td>
                          <td><div align="left">                        wvrhtempwv in
                          wvrhtyrwv                      </div></td>
                          <td><div align="right">                        Peak Wind Gust                      </div></td>
                          <td><div align="left">                        wvhigh18wv at
                          wvhight18wv                      </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        High
                          Since Midnight                      </div></td>
                          <td><div align="left">                        wvhigh01wv
                          at wvhight01wv                      </div></td>
                          <td><div align="right">                        Wind Chill Factor                      </div></td>
                          <td><div align="left">                        wvcur02wv                      </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        Low                      </div></td>
                          <td><div align="left">                        wvlow01wv
                          at wvlowt01wv                      </div></td>
                          <td><div align="right">                        Yesterday Max Wind                      </div></td>
                          <td><div align="left">                        wvyhigh18wv at wvyhight18wv                      </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        Rainfall Since
                          Midnight                      </div></td>
                          <td><div align="left">                        wvcur16wv                      </div></td>
                          <td><div align="right">                        Relative Humidity                      </div></td>
                          <td><div align="left">                        wvcur13wv                      </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        Rainfall Yesterday                      </div></td>
                          <td><div align="left">                        wvyhigh16wv                      </div></td>
                          <td><div align="right">                        Barometric Pressure                      </div></td>
                          <td><div align="left">                        wvcur15wv                      </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        Sunrise                      </div></td>
                          <td><div align="left">                        wvsrisewv                      </div></td>
                          <td><div align="right">                        Heat Index                      </div></td>
                          <td><div align="left">                        wvcur04wv                      </div></td>
                        </tr>
                        <tr>
                          <td><div align="right">                        Sunset                      </div></td>
                          <td><div align="left">                        wvssetwv                      </div></td>
                          <td><div align="right">                        Dew Point                      </div></td>
                          <td><div align="left">                        wvcur03wv                      </div></td>
                        </tr>
                        <tr>
                          <td> </td>
                          <td> </td>
                          <td> </td>
                          <td> </td>
                        </tr>
                        <tr>
                          <td> </td>
                          <td>Moon
                          distance from earth</td>
                          <td><span>wvmdistwv</span></td>
                          <td> </td>
                        </tr>
                        <tr>
                          <td><h2> </h2></td>
                          <td><h2> </h2></td>
                          <td><h2> </h2></td>
                          <td><h2> </h2></td>
                        </tr>
                        <tr>
                          <td><h2><a href="http://www.coastwatch.msu.edu/twomichigans.html" target="_blank">Lake
                            Michigan<br />
       Water Temp</a></h2></td>
                          <td><h2><a href="http://www.woodtv.com/Global/category.asp?C=2906&nav=0Rcf">TV
                          8</a> &amp; <a href="http://www.wzzm13.com/weather/forecast/weather.asp">TV13</a> Weather </h2></td>
                          <td><h2><a href="http://www.deq.state.mi.us/beach/Default.aspx?County=70" target="_blank">Ottawa County Beach Conditions</a></h2></td>
                          <td><h2><a href="http://www.crh.noaa.gov/product.php?site=grr&product=nsh&issuedby=grr" target="_blank">Nearshore
                          Marine Forcast</a></h2></td>
                        </tr>
                      </table>

    Of course as soon as I posted that, I found the error of my ways. I had forgotten to set containerheight:   on my .js script for 'div#featured'
    Arrrghh, why couldn't I have realized that a hour ago!!!

  • Problem with looping logic

    Hello all,
    Ok reposted using code tags, sorry about that.
    I'm trying to write some code to take in a 2D int array, loop through the array to identify where certain blocks of numbers begin and record that location so that I an jump straight to it at a later time. The number blocks go up iteratively from a point from 0 to 9 and are surrounded by nodata values(-9999).
    The problem is that when I print out the numbers they are only being recognised up to 6 (7th number) and when I check the locations against the original text file they dont match. I think it's just a problem with my logic but I'm not sure why.
    The text file is converted to ints and placed in an array from a buffered file reader in a seperate class. I can put this up if needed.
    Any help would be much appreciated.
    Thanks.
    Duncan
    *  Class imports text file which contains a collection of values, either nodata(-9999) or a location
    *  represented by numbers moving away from a point; 0 closest then 1, then 2 etc.
    *  records the first location of each number to avoid having to loop through the whole file each time.
    *  i.e. can later jump straight to the first recorded location of each number.
    *  In current text file there are 10 numbers(0 - 9) but for some reason it stops finding them after
    *  6(seventh no.) and having checked the location values against the original text file these are wrong
    *  by a fair way as well.
    import java.io.*;
    //import java.awt.*;
    //import java.awt.event.*;
    public class Hydrograph {
         int width = 0;
         int height = 0;
         int dZeroC, dZeroD = 0;
         int dOneC, dOneD = 0;
         int dTwoC, dTwoD = 0;
         int dThreeC, dThreeD = 0;
         int dFourC, dFourD = 0;
         int dFiveC, dFiveD = 0;
         int dSixC, dSixD = 0;
         int dSevenC, dSevenD = 0;
         int dEightC, dEightD = 0;
         int dNineC, dNineD = 0;
         public Hydrograph() {
              /* Ignore this bit it's being used for something else
              //File file = new File("c:/Users/Duncan/Documents/MODULES/MSc Dissertation/Code/A1.txt");
              //File file = new File("M:/java/code/A1.txt");
              ArrayRead ar = null;
              ar = new ArrayRead(file);
              int rows = ar.getRows();
              int columns = ar.getColumns();
              int steps = ar.getSteps();
              int[][][] threeDIntArray = ar.getThreeDIntArray();
              // Creates a new instance of delay class which takes in a text file and converts
              // it to int form, placing it into a 2D int array.
              Delay dLay = null;
              dLay = new Delay();
              width = dLay.getWidth();
              height = dLay.getHeight();
              int[][] twoDDelayFile = dLay.getTwoDintArray();
              int delayCount = 0;
              // Loops through 2D int array to identify when number first equals 0, then passes
              // the height and width values to storeDelayPos method below. Then finds for 1, 2
              // 3, 4,...etc by adding 1 to delayCount.
              System.out.println(" ");
              for (int a=0; a<width; a++) {
                   for (int b=0; b<height; b++) {
                        if (twoDDelayFile[a] == delayCount) {
                             int c, d = 0;
                             c = a;
                             d = b;
                             storeDelayPos(c, d, delayCount);
                             System.out.println(delayCount);
                             delayCount++;
                             break;
                   //System.out.println(" ");
              System.out.println(" ");
              System.out.print(dZeroC + " " + dZeroD);
              System.out.println(" ");
              System.out.print(dOneC + " " + dOneD);
              System.out.println(" ");
              System.out.print(dTwoC + " " + dTwoD);
              System.out.println(" ");
              System.out.print(dThreeC + " " + dThreeD);
              System.out.println(" ");
              System.out.print(dFourC + " " + dFourD);
              System.out.println(" ");
              System.out.print(dFiveC + " " + dFiveD);
              System.out.println(" ");
              System.out.print(dSixC + " " + dSixD);
              System.out.println(" ");
              System.out.print(dSevenC + " " + dSevenD);
         // Takes in width, height and delayCount value and sets variables according to
         // the value of delayCount.
         void storeDelayPos (int setC, int setD, int setDCount) {
              int dCount = 0;
              dCount = setDCount;
              switch(dCount) {
                   case 0:
                        dZeroC = setC;
                        dZeroD = setD;
                        break;
                   case 1:
                        dOneC = setC;
                        dOneD = setD;
                        break;
                   case 2:
                        dTwoC = setC;
                        dTwoD = setD;
                        break;
                   case 3:
                        dThreeC = setC;
                        dThreeD = setD;
                        break;
                   case 4:
                        dFourC = setC;
                        dFourD = setD;
                        break;
                   case 5:
                        dFiveC = setC;
                        dFiveD = setD;
                        break;
                   case 6:
                        dSixC = setC;
                        dSixD = setD;
                        break;
                   case 7:
                        dSevenC = setC;
                        dSevenD = setD;
                        break;
                   case 8:
                        dEightC = setC;
                        dEightD = setD;
                        break;
                   case 9:
                        dNineC = setC;
                        dNineD = setD;
                        break;
                   default:
                        System.out.println("OUT OF BOUNDS");
                        break;
         public static void main (String args[]) {
         new Hydrograph();

    Hi,
    I am working on a hydrograph program in java as well... I am trying to represent rainfall data. Do you think that you could share some of the code that you came up with, so that I don't have to go through the whole process.
    thank you so much,
    Kevin

  • JTable - getValueAt Problem

    I am new to Java and am having a problem with a JTable. I want the user to enter 12 months of rain that will go into an array list. The input sreen is O.K., but I cant retrieve the data or clear the cells. Any suggestings would be appreciated. Here is the code. Thanks Ronnie
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.BorderFactory.*;
    import javax.swing.table.*;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JMenuBar;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class GridBagWindow extends JFrame implements ActionListener,
    FocusListener {
    public GridBagWindow() {
    setTitle("User Rainfall Data");
    JComboBox userCboRainCounty, userCboRainYr;
    DefaultTableModel dtmUserRain = new DefaultTableModel();
    JMenuBar userRainJMB = new JMenuBar();
    JMenu userRainfileMenu = new JMenu("File");
    JMenu userRainprintMenu = new JMenu("Print");
    JMenu userRainclearMenu = new JMenu("Clear");
    JMenu userRaintotalsMenu = new JMenu("Totals");
    // Need to add additional menu option because evnet can not be added
    // directly to JMenu
    JMenuItem userRainOpen = new JMenuItem("Open");
    JMenuItem userRainSave = new JMenuItem("Save");
    JMenuItem userRainPrint = new JMenuItem("Print");
    JMenuItem userRainClear = new JMenuItem("Clear");
    JMenuItem userRainTotals = new JMenuItem("Totals");
    userRainJMB.add(userRainfileMenu);
    userRainfileMenu.add(userRainOpen);
    userRainfileMenu.add(userRainSave);
    userRainJMB.add(userRainprintMenu);
    userRainprintMenu.add(userRainPrint);
    userRainJMB.add(userRainclearMenu);
    userRainclearMenu.add(userRainClear);
    userRainJMB.add(userRaintotalsMenu);
    userRaintotalsMenu.add(userRainTotals);
    userRainOpen.addActionListener(this);
    userRainSave.addActionListener(this);
    userRainPrint.addActionListener(this);
    userRainClear.addActionListener(this);
    userRainTotals.addActionListener(this);
    setJMenuBar(userRainJMB);
    Container contentPane = getContentPane();
    setFont(new Font("Arial", Font.BOLD, 16));
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    contentPane.setLayout(gridbag);
    int width = 800;
    int height = 500;
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screen.width - width) / 2;
    int y = (screen.height - height) / 2;
    setBounds(x, y, 600, 600);
    setJMenuBar(userRainJMB);
    JLabel userRainLblCounty = new JLabel(
    " County");
    userRainLblCounty.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 2, 0, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(1, 25, 1, 1);
    gridbag.setConstraints(userRainLblCounty, c);
    contentPane.add(userRainLblCounty);
    userCboRainCounty = new JComboBox();
    userCboRainCounty.setFont(new Font("Arial", Font.BOLD, 16));
    userCboRainCounty.setBackground(Color.white);
    buidConstraints(c, 3, 0, 1, 1, 0, 0);
    c.insets = new Insets(1, 1, 1, 1);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userCboRainCounty, c);
    userCboRainCounty.addFocusListener(this);
    contentPane.add(userCboRainCounty);
    String[] header = { "Jan", "Feb", "Mar", "Apr", "May", "June",
    "July", "Aug", "Sep", "Oct", "Nov", "Dec", "Total" };
    DefaultTableModel dftModel = new DefaultTableModel(header, 1);
    JTable userRainTable = new JTable(dftModel);
    userRainTable.setEnabled(true);
    JScrollPane scrollPane = new JScrollPane(userRainTable);
    buidConstraints(c, 1, 1, 3, 1, 0, 0);
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(10, 10, 1, 1);
    gridbag.setConstraints(scrollPane, c);
    contentPane.add(scrollPane);
    JLabel userRainLblRain = new JLabel("Rain (in)");
    userRainLblCounty.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 0, 1, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userRainLblRain, c);
    contentPane.add(userRainLblRain);
    userRainTable
    .setPreferredScrollableViewportSize(new Dimension(600, 20));
    JLabel userRainLblRainYr = new JLabel("Rainfall Years");
    userRainLblRainYr.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 0, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.SOUTH;
    c.insets = new Insets(0, 1, 1, 1);
    gridbag.setConstraints(userRainLblRainYr, c);
    contentPane.add(userRainLblRainYr);
    userCboRainYr = new JComboBox();
    userCboRainYr.setFont(new Font("Arial", Font.BOLD, 16));
    userCboRainYr.setBackground(Color.white);
    buidConstraints(c, 1, 2, 1, 1, 0, 0);
    c.insets = new Insets(1, 1, 1, 1);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userCboRainYr, c);
    // userCboRainCounty.addFocusListener(this);
    contentPane.add(userCboRainYr);
    JLabel userRainLblTitle = new JLabel("Title");
    userRainLblTitle.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 2, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    // c.insets = new Insets(1, 14,1,1);
    gridbag.setConstraints(userRainLblTitle, c);
    contentPane.add(userRainLblTitle);
    JTextField userRainTxtTitle = new JTextField(18);
    userRainTxtTitle.setFont(new Font("Arial", Font.BOLD, 16));
    buidConstraints(c, 3, 2, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    c.insets = new Insets(1, 1, 1, 1);
    gridbag.setConstraints(userRainTxtTitle, c);
    contentPane.add(userRainTxtTitle);
    JLabel userLblRainBlank = new JLabel(" ");
    buidConstraints(c, 0, 3, 4, 4, 0, 0);
    c.insets = new Insets(15, 15, 1, 1);
    gridbag.setConstraints(userLblRainBlank, c);
    contentPane.add(userLblRainBlank);
    JButton userBtnRainDefault = new JButton(" Default ");
    userBtnRainDefault.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainDefault.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 1, 4, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userBtnRainDefault, c);
    contentPane.add(userBtnRainDefault);
    JButton userBtnRainCancel = new JButton(" Cancel ");
    userBtnRainCancel.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainCancel.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 2, 4, 1, 1, 0, 0);
    c.anchor = GridBagConstraints.CENTER;
    c.insets = new Insets(15, 0, 0, 0);
    gridbag.setConstraints(userBtnRainCancel, c);
    contentPane.add(userBtnRainCancel);
    JButton userBtnRainOK = new JButton(" O.K ");
    userBtnRainOK.setFont(new Font("Arial", Font.BOLD, 16));
    userBtnRainOK.setBorder(BorderFactory.createRaisedBevelBorder());
    buidConstraints(c, 3, 4, 1, 1, 20, 20);
    c.insets = new Insets(15, 0, 0, 150);
    c.anchor = GridBagConstraints.EAST;
    gridbag.setConstraints(userBtnRainOK, c);
    userBtnRainOK.addActionListener(this);
    contentPane.add(userBtnRainOK);
    // //User Definded Cold Protection
    // Input Combo Box for County Selection, two counties per line
    userCboRainCounty.addItem("CHARLOTTE");
    userCboRainCounty.addItem("CITRUS");
    userCboRainCounty.setSelectedIndex(5);
    userCboRainYr.addItem(String.valueOf(1));
    userCboRainYr.addItem(String.valueOf(5));
    userCboRainYr.addItem(String.valueOf(10));
    userCboRainYr.setSelectedIndex(-1);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    pack();
    setVisible(true);
    void buidConstraints(GridBagConstraints c, int gx, int gy, int gw, int gh,
    int wx, int wy) {
    c.gridx = gx;
    c.gridy = gy;
    c.gridwidth = gw;
    c.gridheight = gh;
    c.weightx = wx;
    c.weighty = wy;
    public void focusGained(FocusEvent af) {
    // if(af.getSource() == userRainTable){
    // userRainTable.setBackground(Color.yellow);
    public static void main(String args[]) {
    GridBagWindow window = new GridBagWindow();
    public void actionPerformed(ActionEvent evt) {
    String actionName = evt.getActionCommand();
    System.out.println("Button \"" + actionName + "\" was pressed.");
    // userRainTable.getValueAt(1,1);
    if (actionName == "Clear") {
    for (int i = 0; i > 14; i++) {
    // userRainfallTable.setValueAt(0, 1 , 1);
    System.out.println("Yes Continue");
    if (actionName == "Totals") {
    System.out.println("Yes Continue");
    }

    Hello Ronnie,
    this is a nice little piece of code. ;-)
    No chance of reducing it a little bit just to show the problem?
    And what about making it at least to compile error free? (Just tried on 1.5_06)
    Also place tags around to make it more readable.
    Regards
    J�rg                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Intermittent landline problems

    Ever since moving into my new house in June, the landline has been very unpredictable.  The longest amount of time it has worked consistently is about a week.  It will randomly stop working for any length of time between a day and a few weeks.  Then randomly start working again for between a few hours and a week.
    We have had 2 BT engineers out.  The first one replaced the front of the master socket.  The phone line then worked again for a few days.  The next BT engineer replaced the whole master socket.  Again, the landline worked for a few days and then stopped again.  As explained above, without altering anything, the phone will randomly stop and start working.  We used to assume that water was getting in when it rained (the master socked is located by the front door).  But after unscrewing the master socket (when it stops working), we cannot detect any moisture in the socket, or on the wall.  Also, the times the phone stops working seems unrelated to rainfall.  Any ideas?  This is driving us crazy and BT seem unable to help.
    Thanks

    Thanks for your reply John.  The problem is that whenever the OpenReach engineer comes to the house, they only fix the problem temporarily.  All they seem to want to do is to change the master socket.  When it starts working again (which it seems to always do), they close the fault.  They have done this twice already and I end up taking a day off work just for them to do the same thing again.  I am hoping that someone might have an idea of what the problem could be so I have some suggestions for the engineer.  Thanks again.

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

  • Problem with threads within applet

    Hello,
    I got an applet, inside this applet I have a singleton, inside this singleton I have a thread.
    this thread is running in endless loop.
    he is doing something and go to sleep on and on.
    the problem is,
    when I refresh my IE6 browser I see more than 1 thread.
    for debug matter, I did the following things:
    inside the thread, sysout every time he goes to sleep.
    sysout in the singleton constructor.
    sysout in the singleton destructor.
    the output goes like this:
    when refresh the page, the singleton constructor loading but not every refresh, sometimes I see the constructor output and sometimes I dont.
    The thread inside the singleton is giving me the same output, sometime I see more than one thread at a time and sometimes I dont.
    The destructor never works (no output there).
    I don't understand what is going on.
    someone can please shed some light?
    thanks.
    btw. I am working with JRE 1.1
    this is very old and big applet and I can't convert it to something new.

    Ooops. sorry!
    I did.
         public void start() {
         public void stop() {
         public void destroy() {
              try {
                   resetAll();
                   Configuration.closeConnection();
                   QuoteItem.closeConnection();
              } finally {
                   try {
                        super.finalize();
                   } catch (Throwable e) {
                        e.printStackTrace();
         }

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Problem with threads running javaw

    Hi,
    Having a problem with multi thread programming using client server sockets. The program works find when starting the the application in a console using java muti.java , but when using javaw multi.java the program doesnt die and have to kill it in the task manager. The program doesnt display any of my gui error messages either when the server disconnect the client. all works find in a console. any advice on this as I havent been able to understand why this is happening? any comment would be appreciated.
    troy.

    troy,
    Try and post a minimum code sample of your app which
    does not work.
    When using javaw, make sure you redirect the standard
    error and standard output streams to file.
    Graeme.Hi Graeme,
    I dont understand what you mean by redirection to file? some of my code below.
    The code works fine under a console, code is supposed to exit when the client (the other server )disconnects. the problem is that but the clientworker side of the code still works. which under console it doesnt.
    public class Server{
    ServerSocket aServerSocket;
    Socket dianosticsSocket;
    Socket nPortExpress;
    ClientListener aClientListener;
    LinkedList queue = new LinkedList();
    int port = 0;
    int clientPort = 0;
    String clientName = null;
    boolean serverAlive = true;
    * Server constructor generates a server
    * Socket and then starts a client threads.
    * @param aPort      socket port of local machine.
    public Server(int aPort, String aClientName, int aClientPort){
    port = aPort;
    clientName = aClientName;
    clientPort = aClientPort;
    try{
    // create a new thread
    aServerSocket = new ServerSocket(port) ;
    // connect to the nPortExpress
    aClientListener = new ClientListener(InetAddress.getByName(clientName), clientPort, queue,this);
    // aClientListener.setDaemon(true);
    aClientListener.start();
    // start a dianostic port
    DiagnosticsServer aDiagnosticsServer = new DiagnosticsServer(port,queue,aClientListener);
    // System.out.println("Server is running on port " + port + "...");
    // System.out.println("Connect to nPort");
    catch(Exception e)
    // System.out.println("ERROR: Server port " + port + " not available");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Server port " + port + " not available", JOptionPane.ERROR_MESSAGE);
    serverAlive = false;
    System.exit(1);
    while(serverAlive&&aClientListener.hostSocket.isConnected()){
    try{
    // connect the client
    Socket aClient = aServerSocket.accept();
    //System.out.println("open client connection");
    //System.out.println("client local: "+ aClient.getLocalAddress().toString());
    // System.out.println("client localport: "+ aClient.getLocalPort());
    // System.out.println("client : "+ aClient.getInetAddress().toString());
    // System.out.println("client port: "+ aClient.getLocalPort());
    // make a new client thread
    ClientWorker clientThread = new ClientWorker(aClient, queue, aClientListener, false);
    // start thread
    clientThread.start();
    catch(Exception e)
    //System.out.println("ERROR: Client connection failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client connection failure", JOptionPane.ERROR_MESSAGE);
    }// end while
    } // end constructor Server
    void serverExit(){
         JOptionPane.showMessageDialog(null, "Server ","ERROR: nPort Failure", JOptionPane.ERROR_MESSAGE);
         System.exit(1);
    }// end class Server
    *** connect to another server
    public class ClientListener extends Thread{
    InetAddress hostName;
    int hostPort;
    Socket hostSocket;
    BufferedReader in;
    PrintWriter out;
    boolean loggedIn;
    LinkedList queue;      // reference to Server queue
    Server serverRef; // reference to main server
    * ClientListener connects to the host server.
    * @param aHostName is the name of the host eg server name or IP address.
    * @param aHostPort is a port number of the host.
    * @param aLoginName is the users login name.
    public ClientListener(InetAddress aHostName, int aHostPort,LinkedList aQueue,Server aServer)      // reference to Server queue)
    hostName = aHostName;
    hostPort = aHostPort;
    queue = aQueue;
    serverRef = aServer;      
    // connect to the server
    try{
    hostSocket = new Socket(hostName, hostPort);
    catch(IOException e){
    //System.out.println("ERROR: Connection Host Failed");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort Failed", JOptionPane.ERROR_MESSAGE);     
    System.exit(0);
    } // end constructor ClientListener
    ** multi client connection server
    ClientWorker(Socket aSocket,LinkedList aQueue, ClientListener aClientListener, boolean diagnostics){
    queue = aQueue;
    addToQueue(this);
    client = aSocket;
    clientRef = aClientListener;
    aDiagnostic = diagnostics;
    } // end constructor ClientWorker
    * run method is the main loop of the server program
    * in change of handle new client connection as well
    * as handle all messages and errors.
    public void run(){
    boolean alive = true;
    String aSubString = "";
    in = null;
    out = null;
    loginName = "";
    loggedIn = false;
    while (alive && client.isConnected()&& clientRef.hostSocket.isConnected()){
    try{
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
    if(aDiagnostic){
    out.println("WELCOME to diagnostics");
    broadCastDia("Connect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    out.println("WELCOME to Troy's Server");
    broadCastDia("Connect : client "+client.getInetAddress().toString());
         out.flush();
    String line;
    while(((line = in.readLine())!= null)){
    StringTokenizer aStringToken = new StringTokenizer(line, " ");
    if(!aDiagnostic){
    broadCastDia(line);
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    else{
    if(line.equals("GETIPS"))
    getIPs();
    else{
    clientRef.sendMessage(line); // send mesage out to netExpress
    out.println(line);
    out.flush();
    } // end while
    catch(Exception e){
    // System.out.println("ERROR:Client Connection reset");
                             JOptionPane.showMessageDialog(null, (e.toString()),"ERROR:Client Connection reset", JOptionPane.ERROR_MESSAGE);     
    try{
    if(aDiagnostic){
    broadCastDia("Disconnect : diagnostics "+client.getInetAddress().toString());
    out.flush();
    else {       
    broadCastDia("Disconnect : client "+client.getInetAddress().toString());
         out.flush();
    // close the buffers and connection;
    in.close();
    out.close();
    client.close();
    // System.out.println("out");
    // remove from list
    removeThreadQueue(this);
    alive = false;
    catch(Exception e){
    // System.out.println("ERROR: Client Connection reset failure");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Client Connection reset failure", JOptionPane.ERROR_MESSAGE);     
    }// end while
    } // end method run
    * method run - Generates io stream for communicating with the server and
    * starts the client gui. Run also parses the input commands from the server.
    public void run(){
    boolean alive = true;
    try{
    // begin to life the gui
    // aGuiClient = new ClientGui(hostName.getHostName(), hostPort, loginName, this);
    // aGuiClient.show();
    in = new BufferedReader(new InputStreamReader(hostSocket.getInputStream()));
    out = new PrintWriter(new OutputStreamWriter(hostSocket.getOutputStream()));
    while (alive && hostSocket.isConnected()){
    String line;
    while(((line = in.readLine())!= null)){
    System.out.println(line);
    broadCast(line);
    } // end while
    } // end while
    catch(Exception e){
    //     System.out.println("ERRORa Connection to host reset");
    JOptionPane.showMessageDialog(null, (e.toString()),"ERROR: Connection to nPort reset", JOptionPane.ERROR_MESSAGE);
    try{
    hostSocket.close();
         }catch(Exception a){
         JOptionPane.showMessageDialog(null, (a.toString()),"ERROR: Exception", JOptionPane.ERROR_MESSAGE);
    alive = false;
    System.exit(1);
    } // end method run

  • Problem with Threads and "plase wait..."-Window

    Hi everyone,
    I have a problem that I'm not able to solve in any way... I have a time-consuming task (a file decryption) which I execute in a separate thread; I've used the SwingWorker class, like suggested by sun-tutorial, and it works right. The problem is that I have to wait that the decryption have finished before continuing with program-execution. Therefore I would like to display a "please wait"-window while the task runs. I've tryed all the possible ways I know but the problem is always the same: the waitWindow is displayed empty, the bounds are painted but the contents no; it's only painted when the decrypt-task has finished. Please help me, I have no more resources....
    decrypt-file code:
    public class DecryptFile {
      private String cryptedFileNameAndPath;
      private ByteArrayInputStream resultStream = null;
      // need for progress
      private int lengthOfTask;
      private int current = -1;
      private String statMessage;
      public DecryptFile(String encZipFileNameAndPath) {
        cryptedFileNameAndPath = encZipFileNameAndPath;
        //Compute length of task...
        // 0 for indeterminate
        lengthOfTask = 0;
      public ByteArrayInputStream getDecryptedInputStream() {
        return this.resultStream;
       * Called from ProgressBarDemo to start the task.
      public void go() {
        current = -1;
        final SwingWorker worker = new SwingWorker() {
          public Object construct() {
            return new ActualTask();
        worker.start();
       * Called from ProgressBarDemo to find out how much work needs
       * to be done.
      public int getLengthOfTask() {
        return lengthOfTask;
       * Called from ProgressBarDemo to find out how much has been done.
      public int getCurrent() {
        return current;
      public void stop() {
        current = lengthOfTask;
       * Called from ProgressBarDemo to find out if the task has completed.
      public boolean done() {
        if (current >= lengthOfTask)
          return true;
        else
          return false;
      public String getMessage() {
        return statMessage;
       * The actual long running task.  This runs in a SwingWorker thread.
      class ActualTask {
        ActualTask () {
          current = -1;
          statMessage = "";
          resultStream = AIUtil.getInputStreamFromEncZip(cryptedFileNameAndPath); //here the decryption happens
          current = 0;
          statMessage = "";
      }The code that calls decryption and displays waitWindow
          final WaitSplash wS = new WaitSplash("Please wait...");
          final DecryptFile cryptedTemplate = new DecryptFile (this.templateFile);
          cryptedTemplate.go();
          while (! cryptedTemplate.done()) {
            try {
              wait();
            } catch (Exception e) { }
          this.templateInputStream = cryptedTemplate.getDecryptedInputStream();
          wS.close();Thanks, thanks, thanks in advance!
    Edoardo

    Maybe you can try setting the priority of the long-running thread to be lower? so that the UI will be more responsive...

  • Problem with threads in j2me

    im using jdk 1.6 with java wtk 2.1
    ya i know..
    2.1 is a jdk1.4 source
    but im using souce as 1.4 during compiliation so thats not the prob
    this is my code
    package org.learn;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.Display;
    public class thtest extends MIDlet
    Thread t;
    public void startApp()
    Alert a=new Alert("hello");
    a.setString("hello");
    Alert b=new Alert("world");
    b.setString("world");
    Display d = Display.getDisplay(this );
    d.setCurrent(a);
    t=Thread.currentThread();
    try{
    t.sleep(10000);
    catch (Exception e){}
    d.setCurrent(b);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
    its just supposed to pause between the alerts using threads
    however when i run it using the wtk, the emulator run properly but when i launch the app, it stops executing giving me this:
    "Error verifying method org/learn/thtest startApp()V
    Approximate bytecode offset 49: Inconsistent or missing stackmap at target
    %the stack info%
    Execution completed.
    437782 bytecodes executed
    9 thread switches
    486 classes in the system (including system classes)
    2506 dynamic objects allocated (73832 bytes)
    2 garbage collections (60652 bytes collected)
    Execution completed.
    437782 bytecodes executed
    9 thread switches
    486 classes in the system (including system classes)
    ALERT: java/lang/VerifyError: org/learn/thtest.
    2506 dynamic objects allocated (73832 bytes)
    2 garbage collections (60652 bytes collected)
    please can someone help me out with this, is it an error on my part or do i have to set some option.

    Hi gandalf123,
    First, Thread.sleep is a static method, so you don't need to create a Thread object to use it.
    I think the problem is due to the fact you don't preverify your midlet.
    More over, you don't need to double post your question.

  • Problem with threads and camera.

    Hi everybody!
    I've a problem with taking snapshot.
    I would like to display a loading screen after it take snapshot ( sometimes i
    have to wait few seconds after i took snapshot. Propably photo is being taken in time where i have to wait).
    I was trying to use threads but i didn't succeed.
    I made this code:
    display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while((!performing.isShown()) && (backgroundCamera.isShown())){
                        Thread.yield();
                    notifyAll();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        this.wait();                   
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();This code is sometimes showing performing screen but sometimes no.
    I don't know why. In my opinion performing.isShown() method isn't working correctly.
    Does anyone have some idea how to use threads here?

    Hi,
    I've finally managed to work this fine.
    The code:
           Object o = new Object();
           display.setCurrent(perform);               
            new Thread(new Runnable(){
                public void run() {               
                    while(!performing.isShown()){
                        Thread.yield();
                   synchronized(o) {
                      o.notify();
            }).start();
            new Thread(new Runnable(){
                public void run() {
                    try {
                        synchronized(o) {
                           o.wait(1);
                    } catch(Exception e) {
                        exceptionHandler(e);
                    photo = camera.snapshot();                               
                    display.setCurrent(displayPhoto);
            }).start();

  • Problem with threads and graphics

    I have a thread that chooses paths for a Travelling salesman problem, it then calls a TSPdraw class and passes it the path, which the class then draws. the problem is when i have two threads it creates two windows but only draws a path in one of them. any ideas where i`m going wrong

    Are you using swing components? Swing isn't threadsafe. If you have multiple threads that want to update your UI you need to use the SwingUtilities.invokeLater(...)or invokeAndWait(...). There is a page in the swing tutorial about this at: http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html

Maybe you are looking for

  • Issue with ClientScript.RegisterClientScriptBlock

    I want to get a confirmation from the user via my c# code. I have used the below piece of code but no luck, it is not working. kindly help. string jScript ="alert('Do you want to continue");"; ClientScript.RegisterClientScriptBlock(GetType(), "sas",

  • Business catalyst hosting

    hallo, wie kann ich eine Domain umziehen zu business catalyst und externe Daten zusätzlich zu den Daten aus Muse hosten? Wo finde ich eine Anleitung. Danke.

  • Checking for empty tags using expression builder for XPATH

    I am creating several filters in a mediator for several parallel paths. I am trying to route the mediator to the correct DB adapter based on what tags are empty in the incoming XML. The XML has 1 required tag and 3 optional. So for the expression, I

  • LOCK BOX-forms

    experts- Can u give the brief explnation about the Lock box information there what type of FORMS are used, who is the configured about this one. (for eg:- we are use the forms in APP f110_D_AVIS) AS the same what type of forms are used.(if it is aski

  • Adding custom buttons to the Rich Text Editor in CQ

    Hi, I have added custom buttons to the rich text editor in order to allow our editors to add specific content, such as popovers, custom videos and other data necessary data. I have successfully modifed the Rich Text editor so, that it includes the cu