SqljCircle &JdbcCircle Class(while loop)

Have compiled and run these two clsses but it only seems to be inserting one record from a RADIUS_VALS table into an AREAS table when it should be looping three records, any ideas why the while loop does not seem to be working??
Philip

Do not compare String contents with "==". Use equals().

Similar Messages

  • Using while loops instead of for loops in arrays?

    I am new to java and doing a java tutorial on using arrays and for loops. What im trying to find out is how it is possible to use a while loop instead.
    I would be very grateful if anyone can suggest a way of changing my code to use a while loop.
    The code I have written is:
    public class DetermineGrade
    public static void main(String[]args)
    final char[] mark = {'A','B' ,'C' ,'D' ,'F' };
    char [] grade = new char[5];
    int [] Score ={95,35,65,75};
    for (int i=0; i<4; i++)
    if (Score >= 90)
    grade= mark[0] ;
    else if (Score >=80)
    grade = mark[1] ;
    else if (Score >=70)
    grade = mark[2] ;
    else if (Score >=60)
    grade = mark[3];
    else grade = mark[4];
    for (int i=0; i<4; i++)
    System.out.println("grade = " + Score + ", " + grade);
    Thankyou LB

    Im trying to underdstand the differences in the
    different loops. I can grasp the for loop but I dont
    see how a while loop works, or how it id different
    from the other?
    for (j = INIT; j < MAX; j++) {
        // do stuff
    }is the same as
    j = INIT;
    while (j < MAX) {
        // do stuff
        j++;
    }Lee

  • What's wrong with this while loop?

    Hi, folks. for the code fragment blow, resultSetArray holds two objects of type ResultSet. From those println statement, i can see the whole while loop(the most outter one) process goes alrite the first time right from begining to the end. However, when variable j increases from 0 to 1, the code stops executing at the the line while(rs.next). I just couldnt figure out what causes the problem while i've been fighting with it for several hours. Could someone plz throw me some lights? With your help, i could possibly go to bed before sun rises...
            while(j<resultSetArray.length)
              //for(int j=0; j<resultSetArray.length; j++)
    System.out.println("show me j is called twice " + j);
                   ResultSet rs = resultSetArray[j];
    System.out.println("the converting rs object is called twice and it is not null " + rs);
                  int numWantedColumns = wantedColumnNames.size();
                  //if it's about go or single trip
                  if(j==0 && rs != null)
                      go = new Element("Go");
                       //go.setText("go");
                       //result.addContent(go);
                  //if it's about return trip
                  else if(j==1 && rs != null)
                      back = new Element("Back");
                       //back.setText("back");
                       //result.addContent(back);
                  if(rs!= null)
    System.out.println("this hell is called twice coz it's not null");
                   while(rs.next())
    System.out.println("what about here?");
                        Element flightInfo = new Element("FlightInfo");
         System.out.println("while rs.next() is called");
                        for (int i = 0; i < numWantedColumns; i++)
                           String columnName   = (String)wantedColumnNames.get(i);
         System.out.println("column name is " + columnName);
                           String value = rs.getString(columnName);
          System.out.println("column value is " + value);
                           flightInfo.addContent(new Element(columnName).setText(value));
                        if(j==0)
                           go.addContent(flightInfo);
                        else if(j==1)
                             back.addContent(flightInfo);
                   else if(rs == null)
                        break;
                   j++;
             }

    i've got the problem sort out, eventually. there was actually nothing wrong with the while loop. it was caused by a typo in databse, instead of having Brisbane, i typed Bisbane. The single letter r cost me more than 6 hours to figure it out. it was such a painful feeling while i realized i made a such stupid mistake.
    by the way, as jnw777 mentioned, output rs.next() info instead of the test line. i did try it, however i didnt realize even System.out.println(rs.next()) would cause the cursor move down one row from its current position. so, plus the original while(rs.next()) statement, it was moving the cursor two rows down at a time! And i just couldnt think of this caused me the fact i was only getting the even number row of the ResultSet while i was sniffing the bug from a class with 700+ lines of code. I was so excited and just couldnt stop yelling at the moment i got over it! That was a damn execiting moment...
    now, i am wondering if anyone in this wonderland would like to share his/her stories.

  • Can't break out of a while loop

    Hi, I am doing a networking course, for which an assignment was to write an echo client and server. I did the assignment in Java and it works just fine. However, there is something I don't understand that is bugging me. I wanted a way to stop the server by either detecting when the client entered "quit" or when the user of the server entered "quit". This was not part of the assignment, but after trying many different things I really want to know (1) what I am doing wrong and (2) what the correct way to do things would be.
    I tried to put an "if" clause within the while loop so that if the client entered "quit" the server would detect that, close the socket connections, and break the while loop. But... it seems that I have done this wrong and I am not sure why.
    (Note - I am not a Java programer - just a beginner, and the course in question isn't a programming course. I did the program below by following some brief guidelines/tutorial. I don't even have any books on Java to consult right now - just ordered few from Amazon for any future projects.)
    The code:
    // EchoServer.java     - a simple server program. It listens on a predetermined port for an incoming connection.
    //                After a client connects they can input a line of text and
    //                the server will echo the exact same line back.
    import java.io.*;
    import java.net.*;
    public class EchoServer {
         protected static int DEFAULT_PORT = 3004;
         public static void main (String args[]) throws Exception {
              int portNumber;          
              try {
                   portNumber = Integer.parseInt(args[0]);
              } catch (Exception e) {
                   portNumber = DEFAULT_PORT;
              ServerSocket myServer = null;
                try{
                   myServer = new ServerSocket(portNumber);      
                   System.out.println("Echo Server started. Listening on port " + portNumber);
              } catch (IOException e) {
                   System.out.println("Could not listen on port: " + portNumber);
                   System.out.println(e);
              Socket clientSocket = null;                         
              try{          
                     clientSocket = myServer.accept();
              } catch (IOException e) {
                     System.out.println("Accept failed:  " + portNumber);
                   System.out.println(e);
              BufferedReader input = null;     
              PrintWriter output = null;
              try {               
                   input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                   output = new PrintWriter(clientSocket.getOutputStream(), true);
              } catch (IOException e) {
                   System.out.println(e);
              String theLine;     
              while(true){
                   theLine = input.readLine();
                   output.println(theLine);     
                   output.flush();
                        if (theLine.equals("quit"))  {
                             input.close();
                             output.close();
                             clientSocket.close();
                             myServer.close();     
                             break;
                        }     // end if
              }     // end while     
         }     // end main
    }          // end EchoClient

    A few observations:
    - You might as well exit after you have caught your exceptions, since none of the conditions I see would allow your program to run properly afterwards. You can either do that by a System.exit(int) or a return;
    - Although this s an example program, you should take advantage of doing things right. Addining a try-finally would be good for tidying things up. First declare your variables before the main try, otherwise the finally won't be able to do its job. For example (this won't compile as is):
    Socket clientSocket = null;
    ServerSocket myServer = null;
    InputStream in = null;
    OutputStream out =null;
    try {
      String theLine = null;     
      while( (theLine = input.readLine()) != null ){
        output.println(theLine);     
        output.flush();
        if (theLine.equals("quit"))  {
           break;
      }     // end while
    } catch ( IOException ex ) {
      ex.printStackTrace();
    } finally {
      if ( in != null ) {
         in.close();
      if ( out != null ) {
         out.close();
      // add other conditions to close other closeable objects
    }The reasoning is that if an exception were ever to happen you would be sure that the clean up would be done. In your current example you may risk having an inputstream left open. Also note that BufferedReader.readLine() returns null when its arrived at the end of its content.

  • Getting a for loop inside a while loop

    I've been having problems with the code below. I'm trying to get the 'while' loop to work so that the program will continue to run after a user types in a sentence. This is supposed to print out how many times a letter has been typed when a sentence has been put in, but it's not working right. It just keeps adding the first sentences numbers together even when a new sentence is typed out. I don't know what I'm doing wrong with this 'while' loop.
    import java.util.Scanner;
    import java.util.*;
    public class Count
    public static void main (String[] args)
    String phrase; // a string of characters
    int countBlank; // the number of blanks (spaces) in the phrase
    int length; // the length of the phrase
    int countA = 0; // the number of a's in the phrase
    int countT = 0; // the number of t's in the phrase
    int countE = 0;
    int countS = 0;
    char ch; // an individual character in the string
    Scanner scan = new Scanner(System.in);
    // Print a program header
    System.out.println ();
    System.out.println ("Character Counter");
    System.out.println ();
    // Read in a string and find its length
    System.out.println ("Enter a sentence or phrase ('quit' to quit): ");
    phrase = scan.nextLine();
    length = phrase.length();
    // Initialize counts
    countBlank = 0;
    // a while loop to allow user to keep entering phrases
       while (true)
       String line=scan.nextLine();
              System.out.println("Type quit to quit or enter a new phrase.");
         if(line.equals("quit"))
    break;
    // a for loop to go through the string character by character
    // and count the blank spaces
    for(int i = 0; i < phrase.length(); i++)
    ch = phrase.charAt(i);
    switch (ch)
    case ' ': countBlank++;
    break;
    case 'a':
    case 'A': countA++;
    break;
    case 't':
    case 'T': countT++;
    break;
    case 'e':
    case 'E': countE++;
    break;
    case 's':
    case 'S': countS++;
    break;
    // Print the results
    System.out.println ();
    System.out.println ("Number of blank spaces: " + countBlank);
    System.out.println ("Number of A's: " + countA);
    System.out.println ("Number of T's: " + countT);
    System.out.println ("Number of E's: " + countE);
    System.out.println ("Number of S's: " + countS);
    System.out.println ();
    }

    Ok well I don't really understand what you're saying, but here's an improved version of my code and I can get it to work, but I don't know how to turn the "do while" loop into just a "while" loop.
    import java.util.Scanner;
    public class Count3
         public static void main (String[] args) {
              String      phrase;           // a string of characters
              int      countBlank=0;      // the number of blanks (spaces) in the phrase
              int      length;           // the length of the phrase
              char      ch;                // an individual character in the string
              int      countA=0;       
              int      countE=0;
              int      countS=0;
              int      countT=0;
              String quit = new String("quit"); //String wasn't initialized
              Scanner scan = new Scanner(System.in);
              // Print a program header
              System.out.println ();
              System.out.println ("Character Counter");
              System.out.println ();
              do { //do-while loop
              // Read in a string and find its length
              System.out.println("Enter a sentence or phrase, or type \"quit\" to quit: ");
              phrase = scan.nextLine();
              length = phrase.length();
              // a for loop to go through the string character by character
              // and count the blank spaces, a's, e's, s', and t's
                   for (int i = 0; i <= length-1; i++) {
                        ch = phrase.charAt(i);
                        switch (ch) {
                             case ' ': countBlank++;
                             break;
                             case 'a':
                             case 'A': countA++;
                             break;
                             case 'e':
                             case 'E': countE++;
                             break;
                             case 's':
                             case 'S': countS++;
                             break;
                             case 't':
                             case 'T': countT++;
                             break;
                   // Print the results
                   System.out.println ();
                   System.out.println ("Number of blank spaces: " + countBlank);
                   System.out.println ("Number of a's: " + countA);
                   System.out.println ("Number of e's: " + countE);
                   System.out.println ("Number of s's: " + countS);
                   System.out.println ("Number of t's: " + countT);
                   System.out.println ();
                   countA=0; countE=0; countS=0; countT=0; countBlank=0;
              }while (!(phrase.equalsIgnoreCase(quit)));          
         }//end main
    }//end class Count

  • Incorporate: For, and while loop,a nested pair for both,and to add graphics

    // I have done the class but
    need help one adding one while loop, one for loop, and a nested pair loops using for and while, and if posbile to add on a dynamite graphics. // i am doing this for a brithday present for my brother who is a java programer
    and would be happy to see his little brother make a java programe for him
    //class file
    import java.awt.*;
    public class ZZZCalculator
            private double amount;
            public ZZZCalculator (double x)
                    amount= x;
            public void addAmt (double inputNumber)
                    amount= amount +inputNumber;
            public void divideAmt (double inputNumber)
                    amount=amount/inputNumber;
            public void subtractAmt (double inputNumber)
                    amount=amount-inputNumber;
            public void multiplyAmt (double inputNumber)
                    amount=amount*inputNumber;
            public void display (Graphics g)
                    g.drawString (""+ amount, 150,100);
            public void setAmt(double x)
                    amount= x;
      // Pgm file
    import java.awt.*;
    import java.applet.Applet;
    import java.awt.event.*;
    public class ZZZCalc extends Applet implements ActionListener {
            ZZZCalculator henrietta;
            TextField amtPlace;
            Button adder;
            Button divide;
            Button subtract;
            Button multiply;            
            public void init()
                    henrietta=new ZZZCalculator(0.0);
                    amtPlace=new TextField(10);
                    amtPlace.addActionListener(this);
                    add(amtPlace);
                    adder=new Button ("+");
                    adder.addActionListener(this);
                    add(adder);
                    divide=new Button ("/");
                    divide.addActionListener(this);
                    add(divide);
                    subtract=new Button ("-");
                    subtract.addActionListener(this);
                    add(subtract);
                    multiply=new Button ("*");
                    multiply.addActionListener(this);
                    add(multiply);
            public void paint (Graphics g)
                    g.drawString("amount:", 100,100);
                    henrietta.display(g);
            public void actionPerformed(ActionEvent e)
                    if (e. getSource()==amtPlace)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta.setAmt(amt);
                    repaint();
                    if(e.getSource()==adder)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta.addAmt(amt);
                    repaint();
                    if(e.getSource()==divide)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta.divideAmt(amt);
                    repaint();
                    if(e.getSource()==subtract)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta.subtractAmt(amt);
                    repaint();
                    if(e.getSource()==multiply)
                    double amt= Double.parseDouble (amtPlace.getText());
                    henrietta. multiplyAmt(amt);
                   repaint();
    //thank you for the help
    i have just started working on java and this is my frist program i am working on and any help i can get would inprove my understanding of java.
    Thank you very much for you help

    hey there... this is Rebecca
    try this somewhere in the prog.
    n = Math.pow(x,y)
    where n is an int you declare...
    and x and y are the numbers... as in
    n = 10^3
    where 10 = x and 3 = y

  • Problem with while loop in thread: starting an audiostream

    Hello guys,
    I'm doing this project for school and I'm trying to make a simple app that plays a number of samples and forms a beat, baed on which buttons on the screen are pressed, think like fruity loops. But perhaps a screenshot of my unfnished GUI makes things a bit more clear:
    [http://www.speedyshare.com/794260193.html]
    Anyway, on pressing the play button, I start building an arraylist with all the selected samples and start playing them. Once the end of the "screen" is reached it should start playing again, this is the while loop:
    public void run(){
            //System.out.println("Wavfiles.size =" + getWavfiles().size());
            System.out.println(repeatperiod);
            if (getWavfiles() == null) {
                System.out.println("Error: list of Wavfiles is empty, cannot start playing.");
            else{
                if(!active) return;
                while(active){
                    System.out.println("Wavfiles.size =" + getWavfiles().size());
                    for (int i=0; i<getWavfiles().size(); i++){
                        Wavplayer filePlayer = new Wavplayer(getWavfiles().get(i).getStream());
                        Timer timer = new Timer();
                        //timer.scheduleAtFixedRate(filePlayer, getWavfiles().get(i).getStartTime(),repeatperiod);
                        timer.schedule(filePlayer, getWavfiles().get(i).getStartTime());
                    try {
                        Thread.sleep(repeatperiod);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(LineBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }But once the second iteration should begin, I'm getting nullpointerexceptions. These nullpointerexceptions come exactly when the second period starts so I suppose the sleep works :-) The nullpointerexception comes from the wavfile I try to play. Wavfile class:
    package BeatMixer.audio;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.TimerTask;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.UnsupportedAudioFileException;
    public class Wavplayer extends TimerTask {
            private SourceDataLine auline;
            private AudioInputStream audioInputStream;
         private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
         public Wavplayer(ByteArrayInputStream wavstream) {
              try {
                   audioInputStream = AudioSystem.getAudioInputStream(wavstream);
              } catch (UnsupportedAudioFileException e1) {
                   e1.printStackTrace();
                   return;
              } catch (IOException e1) {
                   e1.printStackTrace();
                   return;
                    AudioFormat format = audioInputStream.getFormat();
              DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
                    try {
                   auline = (SourceDataLine) AudioSystem.getLine(info);
                   auline.open(format);
              } catch (LineUnavailableException e) {
                   e.printStackTrace();
                   return;
              } catch (Exception e) {
                   e.printStackTrace();
                   return;
        @Override
         public void run() {
                    System.out.println(auline);
              auline.start();
              int nBytesRead = 0;
              byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
              try {
                   while (nBytesRead != -1) {
                        nBytesRead = audioInputStream.read(abData, 0, abData.length);
                        if (nBytesRead >= 0)
                             auline.write(abData, 0, nBytesRead);
              } catch (IOException e) {
                   e.printStackTrace();
                   return;
              } finally {
                   auline.drain();
                   auline.close();
    }auline is null on second iteration, in fact, getAudioInputStream doesn't really work anymore, and I don't know why because I don't change anything about my list of wavfiles as far as I know... Any thoughts or extra info needed?
    Edited by: Lorre on May 26, 2008 12:22 PM

    Is my question not clear enough? Do you need more info? Or is nobody here familiar with javax.sound.sampled?
    Edited by: Lorre on May 26, 2008 2:07 PM

  • Problem with While Loop.

    Hi guys,
    i'm doing a pass exam java question, below is the question criteria.
    Write a program that allows a user to enter their mark attained in each unit and displays their grade. After all marks are entered the average mark is displayed.
    The main method should:
    Prompt the user to enter the number of units taken (check for NumberFormatException)
    Write a for loop to repeat for each subject, where each iteration
    Prompts the user to enter a mark ( a double) for unit 1, unit 2 etc. This should be in a while loop so if mark entered is less than 0 or greater than 100 the prompt will be repeated.
    Pass the mark to a method called getGrade.
    Display the returned grade
    Accumulate each mark
    Print the average mark to 2 decimal places
    The getGrade method should:
    Accept the parameter passed from the main method
    Determine the grade according to the following scale
    Return the grade
    The words that i highlighted in bold is the criteria.
    As you can see from the above question, i create an array , even though the question does not prompt me to create as what i know from tackling JavaQuestions "if it does not prompt me to add a criteria, it is ok to add it" :)
    below is my program code , in which the result i get is the same as the question result. BUT, from the above question it ask me to add a while loop, so if mark entered is less than 0 or greater than 100 the prompt will be repeated.
    But instead i use a do loop. :(
    so can anyone help me or show me how to create the while loop for mark entered is less than 0 or greater than 100 the prompt will be repeated, from my program code below. cause i want to know whether it possible to have a while loop instead of do loop for the my program and the while loop can work with an array criteria.
    thanks
    htw.
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Mark
        public static void main (String [] args)
            String unitStr;
            String markEnterStr;
            int validUnit;
            double total = 0;
            boolean validInput = true;
            DecimalFormat fmt = new DecimalFormat("#0.00");
            while (validInput)
            unitStr = JOptionPane.showInputDialog(null,"Enter number of units: ");
            try
            validUnit = Integer.parseInt(unitStr);
            double[] markArray = new double[validUnit];
            validInput = false;
            for (int index = 0;index < validUnit; index++)
                do
                markEnterStr = JOptionPane.showInputDialog("Please enter mark " +(index+1) +":");           
                markArray[index] = Double.parseDouble(markEnterStr);
                while(markArray[index] < 0 || markArray[index] >100);
                String correctMark = getGrade(markArray[index]);
                System.out.println(correctMark);
                total = total + markArray[index];       
            double average = (double)total / validUnit;
            System.out.println("Average = " +fmt.format(average));                   
            catch (NumberFormatException e)
            public static String getGrade(double x)
                String grade;
                if (x < 50)
                grade = "Fail";
                else if (x < 60)
                grade = "Pass";
                else if (x < 70)
                grade = "Credit";
                else if (x < 80)
                grade = "Distinction";
                else grade = "High distinction";
                return grade;
    }

    Hope u got it.
               markArray[index] = -1;
                while(markArray[index] < 0 || markArray[index] >100);
                markEnterStr = JOptionPane.showInputDialog("Please enter mark " +(index+1) +":");           
                markArray[index] = Double.parseDouble(markEnterStr);
                }VJ

  • While loop

    I am new to Java and need some assistance with the following program:
    Write a program that asks for the user's name and then writes that name to the monitor with either "Ms." or "Mr." in front, depending if the name is for a female or male. Assume that the only female names are
    * Amy
    * Buffy
    * Cathy
    and that the only male names are
    * Elroy
    * Fred
    * Graham
    All other names will be echoed without a title. The program continues looping until the user hits "enter" without first typing a name.
    C:\>java Title
    Enter a name:
    Amy Johnson
    Ms. Amy Johnson
    Enter a name:
    Fred Smith
    Mr. Fred Smith
    Enter a name:
    Zoltan Jones
    Zoltan Jones
    Enter a name:
    C:\>
    Hints: Use a Scanner to read user input. Uses a while loop that tests the length of the input line. Use startsWith() to test the names.
    Here's what I have so far:
    import java.util.*;
    public class TitleApplier
          * @param args
         public static void main(String[] args)
              Scanner scan = new Scanner (System.in);
              System.out.println ("Please enter your name:");
              String name = scan.nextLine();
              while (name.startsWith("A"))
                   System.out.println ("Ms. ".concat (name));
                   if (name.startsWith ("B"))
                        System.out.println ("Ms. ".concat (name));
                   if (name.startsWith ("C"))
                        System.out.println ("Ms. ".concat (name));
                   if (name.startsWith ("E"))
                        System.out.println ("Mr. ".concat (name));
                   if (name.startsWith ("F"))
                        System.out.println ("Mr. ".concat (name));
                   if (name.startsWith ("G"))
                        System.out.println ("Mr. ".concat (name));
                   else
                        System.out.println (name);
    Here are the problems are I am having:
    I am asked to use a while loop that tests the length of the input, I am not sure how I would go about doing that.
    When I enter Amy the program keeps looping, but it does not do that for any other name.
    When I enter any of the other names, I get two outputs one with a title and one right below that with out the title. Is there a way to get one output, the one with the title?

    ChavezOA wrote:
    I am asked to use a while loop that tests the length of the input, I am not sure how I would go about doing that.
    When I enter Amy the program keeps looping, but it does not do that for any other name. You need to familiarize yourself with logic statments... specifically the use of or "||" also and "&&"... (condition1) || (condition2) || ...
    When I enter any of the other names, I get two outputs one with a title and one right below that with out the title. Is there a way to get one output, the one with the title?As already stated, you have independent "if" statements, you need to link them together somehow...
    if() {
      //what ever
      else if() {
        //what ever
      else if() {
        //what ever
      }

  • While loop problem

    I have a problem with a while loop in this code and it is really holding me up doing my degree. I can see nothing wrong with it but perhaps someone here can help. I would be really greatful if someone could. I have commented the line where the while loop starts about a third of the way down the code.
    Thanks
    Michael
    if (ae.getSource()==client_open)
    int row=0;
    check=true;
    row=client_listing.getSelectedRow();
    try
    System.out.println("information[row][1] is "+information[row][1]);
    if(information[row][1]!=null) //if the index is not null. Comment out this if statement to troubleshoot
    try
    InetAddress inet=InetAddress.getByName(information[row][1]);
    //Create a client socket on the listeners machone on port 7070
    client_socket=new Socket(inet,7070);
    System.out.println("Client port open on 7070 ");
    //Get the output as well as the input streams on that socket
    BufferedOutputStream out=new BufferedOutputStream(client_socket.getOutputStream());
    BufferedInputStream br_socket=new BufferedInputStream(client_socket.getInputStream());
    XMLWriter writer=new XMLWriter();
    writer.requestFString("SHOWFILES"," ");
    String file_data=writer.returnRequest();
    byte file_bytes[]=file_data.getBytes();
    int file_size=file_bytes.length;
    byte b[]=new byte[1024];
    // The methos takes a byte array and it's length as parameters and return
    // a byte array of length 1024 bytes....
    add_on upload=new add_on();
    System.out.println("Class of add_on created sucessfully");
    b=upload.appropriatelength(file_bytes,file_size);
    out.write(b,0,1024);
    /*An output stream is also initialised. This is used to store all the response
    from the listener */
    BufferedOutputStream out_file=new BufferedOutputStream(new FileOutputStream("response.xml"));
    int y=0;
    byte f[]=new byte[32];
    System.out.println("Entering while loop");
    //This while loop is not working. Any ideas. It just hangs here
    while((y=br_socket.read(f,0,32))>0) //the socket input stream is read
    out_file.write(f,0,y); //written on to the file output stream, y bytes from f start @ ofset 0
    out.close();
    br_socket.close();
    out_file.close();
    System.out.println("Exited while loop and closed streams");
    catch(Exception e)
    client_socket=null;
    check=false;
    System.out.println("Didnt enter try");
    try
    client_socket.close();
    catch(Exception e)
    System.out.println("Error occuered "+e.getMessage());
    row=0;
    if(check) //If the exception occurs then do not come here
    Vector parameters=new Vector();
    // A class SParser is also used here this class has a function/method of
    // the name perform which calls the xml parser to parse the xml file
    // generated by the response from the client soket...
    // the function perform returns a Vector which has the files/directories,
    // along with their flag information and size in case of files....
    SParser sp=new SParser();
    System.out.println("SParser object created sucessfully");
    parameters=sp.perform("response.xml");
    System.out.println("Parsing finished ");
    // The vector value returned by the xml parseris then passed as one of
    // the parameters to a class named file_gui this class is responsible for
    // displaying GUI consisting of a table and some buttons along with the
    // root information and flag..
    // Initially since the class is called for the first time the parameter
    // for the root is given the name "ROOT" and the Flag is set to "0"..
    file_gui showfiles=new file_gui(parameters,information[row][1],"Root","0");
    showfiles.show();
    check=false;
    } //end if
    } // end if
    } //end try
    catch(Exception e)
    row=0;
    } //end of ae.getSource()

    Why do you think it hangs at the while loop, eh? You need to put in additional printlns to justify your assertion. It takes alot less time to diagnose if you put in specific try/catch blocks with their own printlns - even if it is not as much fun. When you get into these kinds of troubles, there is no shame in putting in prints at each statement or logical point to track down the actual fault.
    ~Bill

  • Problem with while loops, please help!

    I am having quite a bit of trouble with a program im working on. What i am doing is reading files from a directory in a for loop, in this loop the files are being broken into words and entered into a while loop where they are counted, the problem is i need to count the words in each file seperately and store each count in an array list or something similar. I also want to store the words in each file onto a seperate list
    for(...)
    read in files...
         //Go through each line of the first file
              while(matchLine1.find()) {
                   CharSequence line1 = matchLine1.group();
                   //Get the words in the line
                   String words1[] = wordBreak.split(line1);
                   for (int i1 = 0, n = words1.length; i1 < n; i1++) {
                        if(words1[i1].length() > 0) {
                             int count= 0;
                                           count++;
                             list1.add(words1[i1]);
              }This is what i have been doing, but with this method count stores the number of words in all files combined, not each individual file, and similarly list1 stores the words in all the files not in each individual file. Does anybody know how i could change this or what datastructures i could use that would allow me to store each file seperately. I would appreciate any help on this topic, Thanks!

    Don't try to construct complicated nested loops, it makes things a
    tangled mess. You want a collection of words per file. You have at least
    zero files. Given a file (or its name), you want to add a word to a collection
    associated with that file, right?
    A Map is perfect for this, i.e. the file's name can be the key and the
    associated value can be the collection of words. A separate simple class
    can be a 'MapManager' (ahem) that controls the access to this master
    map. This MapManager doesn't know anything about what type of
    collection is supposed to store all those words. Maybe you want to
    store just the unique words, maybe you want to store them all, including
    the duplicates etc. etc. The MapManager depends on a CollectionBuilder,
    i.e. a simple thing that is able to deliver a new collection to be associated
    with a file name. Here's the CollectionBuilder:public interface CollectionBuilder {
       Collection getCollection();
    }Because I'm feeling lazy today, I won't design an interface for a MapManager,
    so I simply make it a class; here it is:public class MapManager {
       private Map map= new HashMap(); // file/words association
       CollectionBuilder cb; // delivers Collections per file
       // constructor
       public MapManager(CollectionBuilder cb) { this.cb= cb; }
       // add a word 'word' given a filename 'name'
       public boolean addWord(String name, String word) {
          Collection c= map.get(name);
          if (c == null) { // nothing found for this file
             c= cb.getCollection(); // get a new collection
             map.put(name, c); // and associate it with the filename
          return c.add(word); // return whatever the collection returns
       // get the collection associated with a filename
       public Collection getCollection(String name) { return map.get(name); }
    }... now simply keep adding words from a file to this MapManager and
    retrieve the collections afterwards.
    kind regards,
    Jos

  • Trouble with while loop, not sure what to put in it in my project

    I'm making a class to a simple command line craps game. I must use a while loop to implement craps rules. The rules that i was given are:
    if your first roll is a 4, 5, 6, 8, 9, or 10, you roll again until either you get a 7 (you lose) or you get the number from your first roll. (i thought 7 or 11 wins, like in the next example)
    yeah, thats right, not very good directions. The first directions i had for a different way of doing it using if and else statements were:
    The player rolls the two dice.
    If the sum of the resulting die values is 7 or 11, the player wins.
    If the sum is 2, 3, or 12, the player loses.
    If something else is rolled, the player has to roll again to determine the outcome.
    If the sum of the second roll is the same as what the player rolled the first time, the player wins. Otherwise the player loses.
    (You might get a pair of dice and play a few rounds to try it.)
    here's my code that i have so far for my craps class, in the middle section, i have previous code that i used for if else statements, that is what im trying to replace: package games;public class Craps {
    private Dice dice1;
    private Dice dice2;
    private int gamesPlayed;
    private int gamesWon;
    private boolean lastGameWon;
    private boolean gameOver;
    private int firstRoll;
    private int secondRoll;
    public Craps() {
    dice1 = new Dice(6);
    dice2 = new Dice(6);
    gamesPlayed = 0;
    gamesWon = 0;
    lastGameWon = false;
    firstRoll = 1;
    secondRoll = 2;
         //returns firstroll
    public int getFirstRoll(){
    return firstRoll;
         //returns secondroll
    public int getSecondRoll(){
    return secondRoll;
    public int getGamesPlayed(){
    return gamesPlayed;
    public int getGamesWon(){
    return gamesWon;
    public boolean lastGameWon(){
    return lastGameWon;
         public int nextSum()
         dice1.roll();
         dice2.roll();
         return dice1.getSideUp() + dice2.getSideUp();
    public void play()
              firstRoll = nextSum();
    if (firstRoll == 7 || firstRoll == 11)
              gameOver = true;
              gamesWon++;
              if (firstRoll == 2 || firstRoll == 3 || firstRoll == 12)
              gameOver = true;
                   else{
                   gameOver = false;
              while (gameOver == false)
              secondRoll++;
    public String toString()
    return "games - " + gamesPlayed + ", won - " + gamesWon + ", last game won - " + lastGameWon + " First Roll - " + firstRoll +
    ", Second Roll - " + secondRoll;
    i'm really confused on how to get the while loop will keep starting the game over if it is false, am i using the right approach? Also i have to use a while loop, its for a school project.
    thanks.

    The code you asked for could be:
    package games;
    public class Craps {
        private Dice dice1;
        private Dice dice2;
        private int gamesPlayed;
        private int gamesWon;
        private boolean lastGameWon;
        private boolean gameOver;
        private int firstRoll;
        private int secondRoll;
        public Craps()
            dice1 = new Dice(6);
            dice2 = new Dice(6);
            gamesPlayed = 0;
            gamesWon = 0;
            lastGameWon = false;
            firstRoll = 1;
            secondRoll = 2;
         //returns firstroll
        public int getFirstRoll(){
            return firstRoll;
         //returns secondroll
        public int getSecondRoll(){
            return secondRoll;
        public int getGamesPlayed(){
            return gamesPlayed;
        public int getGamesWon(){
            return gamesWon;
        public boolean lastGameWon(){
            return lastGameWon;
        public int nextSum()
            dice1.roll();
            dice2.roll();
            return dice1.getSideUp() + dice2.getSideUp();
        public void play() {
            gamesPlayed++;
            firstRoll = nextSum();
            if (firstRoll == 7 || firstRoll == 11)
                gamesWon++;
                lastGameWon = true;
            else if (firstRoll == 2 || firstRoll == 3 || firstRoll == 12)
                lastGameWon = false;
            else
               secondRoll = nextSum();
               if (firstRoll == secondRoll)
                  gamesWon++;
                  lastGameWon = true;
               else
                  lastGameWon = false;
        public String toString()
            return "games - " + gamesPlayed + ", won - " + gamesWon + ", last game won - " + lastGameWon + " First Roll - " + firstRoll +
                    ", Second Roll - " + secondRoll;
    }I'm not sure of craps rules, the code above makes a first roll and if game isn't won or lose at once (7 and 11 wins, 2,3 or 12 lose) a second roll is done. If the second roll is equals to the first made then the game is won else the game is lose. Is it right?

  • Help with a while loop condition

    I'm trying to write to a File. I ask the user for input, then I enter a while loop and test the condition. The loop works, but it won't stop. I've tried everything. Here is my code please help!!
    thanks
    inputline = keyboard.readLine();//read the keyboard
    try{
    while( inputline != null ){
    DiskOut.println( inputline );
    DiskOut.flush();
    inputline = keyboard.readLine();//read the keyboard again
    }//end while
    }//end try
    catch (IOException e) { 
    e.printStackTrace();
    }//end catch
    also i've tried these while loop conditions:
    while(inputline != "\n" || inputline != "\r") and the sort

    while(inputline != "\n" || inputline != "\r")The condition
    X!=Y OR X!=Z (given Y != Z)
    is always true. X will always not be equal to at least one of the values. So you'll want to use:
    while(!inputline.equals("\n") && !inputline.equals("\r"))In other words, "while inputline is not equal to either of them". Note the use of && instead of ||.
    If "keyboard" is simply a BufferedReader on top of System.in (and not your own class), the trailing line feeds and carriage returns won't even be in the string returned by readLine(). Your best bet is this:
    while(null != inputline && 0 != inputline.length())Make sure you type the two parts of that AND condition in the order above. If for whatever reason there are trailing \r and \n on the strings, you'll want to accomodate for platforms that may include both characters.
    // trim the trailing newline characters
    while(inputline.endsWith("\r") ||
          inputline.endsWith("\n")) {
       inputline = inputline.substring(0,inputline.length()-1);
    // or maybe this will work if you don't mind losing
    //  the whitespace at the beginning of the string:
    inputline = inputline.trim();Hope that helps somewhat.

  • Circular linked list while loop

    i have a circular linked list and i'd like a while loop to iterate though all of them. my problem is that it always excludes the last node. i know why, it's due to the fact that "current.next != alive" skips it from ever accessing the last node. i can't seem to solve it. note that the last node in the list points to the first node (alive):
                   while(current.next != alive )
                        prev = prev == null ? prev = alive : prev;
                        //identify the name with it's matching node
                        if(name.equals(current.name.toLowerCase()))
                             prev.next = current.next;
                             dead = current;
                             current = current.next;
                             dead.next = null;
                             while(dead.next != null)
                                  dead = dead.next;
                        else
                             prev = current;
                             current = current.next;     
                   }

    //this class assists the client in managing a game of assassinations. it does so by providing options such as verifying a target's existence, getting the list of dead people, getting the lsit of alive people, and moving people from the alive to dead list
    public class AssassinManager
         private AssassinNode alive;
         private AssassinNode alive_tail;
         private AssassinNode dead;
         //pre: must send a string array
         //post: nodes are created
         public AssassinManager(String[] names)
              dead = null;
              alive = new AssassinNode(names[0]);
              AssassinNode current = alive;
              System.out.println(names[0] + " is first, " + names[(names.length-1)] + " is last\n\n");
              for(int i = 1; i < names.length; i++)
                   while(current.next != null)
                        current = current.next;
                   current.next = new AssassinNode(names);
              alive_tail = current.next = new AssassinNode(names[(names.length - 1)], alive);
         //post: outputs all the people still alive
         public void printKillRing()
              AssassinNode last = null, current = alive;
              while(current.next!= alive)
                   System.out.println(current.name + " is stalking " + current.next.name);
                   last = current.next;
                   current = current.next;
              System.out.println(current.name + " is stalking " + alive.name);
         //post: outputs a list of the dead people
         public void printGraveyard()
              AssassinNode last = null, current = dead;
              while(dead != null)
                   System.out.println(current.name + " was killed by " + current.killer);
                   last = current.next;
                   current = current.next;
         //pre: must send a string name
         //post: will return true/false depending on the input if the name is in the killing ring (alive)
         public boolean killRingContains(String name)
              AssassinNode current = alive;
              name = name.toLowerCase();
              while(current.next!= alive)
                   if(name.equals(current.name.toLowerCase()))
                        return true;
                   current = current.next;
              return false;
         //pre; must send a string name
         //post: will return true/false if the name is in the graveyard list
         public boolean graveyardContains(String name)
              AssassinNode current = dead;
              name = name.toLowerCase();
              while(dead != null && current.next != null)
                   if(name.equals(current.name.toLowerCase()))
                        return true;
                   current = current.next;
              return false;
         //post: checks if game is over by seeing if there is more than 1 player
         public boolean gameOver()
              AssassinNode current = alive;
              if(current.next == null)
                   return true;
              return false;
         //post: outputs the winner's name
         public String winner()
              AssassinNode current = alive;
              if(current.next == null)
                   return alive.name;
              return null;
         //pre: must send a string name that exists is alive
         //post: will remove the user from the alive list and add it to the killed list
         public void kill(String name)
              //check if person exists to remove them from alive list
              if(killRingContains(name.trim()) == true)
                   AssassinNode prev = null, current = alive, dead = this.dead;
                   name = name.toLowerCase();
                   while(current != null)
                        System.out.println(current.name);
                        if(name.equals(current.name.toLowerCase()))
                             prev = prev == null ? alive_tail : prev;
                             prev.next = current.next;
                             //dead = dead == null ? current : dead;
                             //while(dead.next != null)
                                  //dead = dead.next;
                             if(prev.next == alive)
                                  break;
                             current = prev.next;
                        else
                             if(current.next == alive)
                                  break;
                             prev = current;
                             current = current.next;
    }Edited by: ixxalnxxi on Apr 27, 2008 12:58 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Problem writing condition of a while loop

    I'm receiving an error when attempting to compile my class.
    while(numItems != 1 || 2 || 3) (numItems is an integer variable)
    Basically, using the Scanner class, I request an integer input from the user, and that input needs to be either 1, 2 or 3, so I have included the while loop as a validation tool, so that whenever the user's input is NOT 1 or 2 or 3, the system prints out an error message and the user has to reenter. However, the code above is highlighted when I compile, and the error description states that I cannot use the || operator for the int data type. I wasn't sure if the OR operator was two || pipes or one, but I receive the same error regardless.
    Is there a way around this?
    Thank you.

    ryanz0r wrote:
    I'm receiving an error when attempting to compile my class.
    while(numItems != 1 || 2 || 3) (numItems is an integer variable)
    Basically, using the Scanner class, I request an integer input from the user, and that input needs to be either 1, 2 or 3, so I have included the while loop as a validation tool, so that whenever the user's input is NOT 1 or 2 or 3, the system prints out an error message and the user has to reenter. However, the code above is highlighted when I compile, and the error description states that I cannot use the || operator for the int data type. I wasn't sure if the OR operator was two || pipes or one, but I receive the same error regardless.
    Is there a way around this?Hi, Ryaz0r.
    In conjunction with Encephalopathic's syntax question for your valid boolean expression, you'll also have to replace the || operators with the && operators to achieve your described condition.
    -- L. James
    L. D. James

Maybe you are looking for

  • I want this on Scot McNealy�s desk by tomorrow.

    The java technology has evolved nicely over the years. It is doing very well on the server side; on the mobile side all the major players are announcing java enabled devices. But on the side where you expect people to really get acquainted with the j

  • How to create a Payment Form for access to multiple secure zones

    I'm trying to create a Payment Form that allows the user to select from a dropdown of videos, each of which represents a secure zone page with an embedded video. What I can't figure out -- and tech chat can't help -- is how to redirect the user to th

  • Transactional access to Communications and System ID

    Hello Experts, Can the communications Id execute transactions in SAP other than performing RFC execution? Is it a suggested solution to let these non-dialog id's have transactional access from Audit perspective? Appreciate your inputs. Regards, Sande

  • HT1926 Error during install.

    I get the message: An error occurred during the installation of assembly "Microsoft.VC80.CRT,type="32",version="8.0.50727.4053".publicKeyToken="1fc8b3b9 a1e18e3b".processorArchitecture="amd64"". Please Refer to Help and Support for more information.

  • Scan IP confusion while implementing ORACLE apps R12 with 11gR2

    Hi All, We are planning to implement a R12 apps with 11.2.0.3. As i know that when we install oracle 11gR2.scan listener and scan vip got created in GRID_HOME. The scan listener comes with default port. As R12 by default comes with 11.1.0.7. As per o