Subtle bug in Deitel & Deitel "Java How to Program" book

Merry x mas and happy new year, guys.
I have this applet (which is at the same time runnable and listener) its printed in Deitel & Deitel "Java How to Program" book 3rd ed.
The program works but as you turn on and off the "suspend" checkboxes some of the threads are not notified, so they go to infinite wait state, deadlock. I couldn't figure out what is wrong or how to fix the problem.. please read the code below, or copy and paste this code to your eclipse, its just one file, then play with the check boxes, some of the threads don't wake up after wait... technically they don't shift from WAITING to TIMED_WAITING state.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
* @author
// Fig. 15.7: RandomCharacters.java
// Demonstrating the Runnableinterface
public class RandomCharacters extends JApplet implements Runnable, ActionListener {
    private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private JLabel outputs[];
    private JCheckBox checkboxes[];
    private final static int SIZE = 3;
    private Thread threads[];
    private boolean suspended[];
    public void init() {
        outputs = new JLabel[SIZE];
        checkboxes = new JCheckBox[SIZE];
        threads = new Thread[SIZE];
        suspended = new boolean[SIZE];
        Container c = getContentPane();
        c.setLayout(new GridLayout(SIZE, 2, 5, 5));
        for (int i = 0; i < SIZE; i++) {
            outputs[i] = new JLabel();
            outputs.setBackground(Color.green);
outputs[i].setOpaque(true);
c.add(outputs[i]);
checkboxes[i] = new JCheckBox("Suspended");
checkboxes[i].addActionListener(this);
c.add(checkboxes[i]);
public void start() {
// create threads and start every time start is called
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(this, "Thread " + (i + 1));
threads[i].start();
public void run() {
Thread currentThread = Thread.currentThread();
int index = getIndex(currentThread);
char displayChar;
while (threads[index] == currentThread) {
// sleep from 0 to 1 second
try {
Thread.sleep((int) (Math.random() * 1000));
synchronized (this) {
while (suspended[index]
&& threads[index] == currentThread) {
wait();
} catch (InterruptedException e) {
System.err.println("sleep interrupted");
displayChar = alphabet.charAt(
(int) (Math.random() * 26));
outputs[index].setText(currentThread.getName() + ": " + displayChar);
System.err.println(currentThread.getName() + " terminating");
private int getIndex(Thread current) {
for (int i = 0; i < threads.length; i++) {
if (current == threads[i]) {
return i;
return -1;
public synchronized void stop() {
// stop threads every time stop is called
// as the user browses another Web page
for (int i = 0; i < threads.length; i++) {
threads[i] = null;
notifyAll();
public synchronized void actionPerformed(ActionEvent e) {
for (int i = 0; i < checkboxes.length; i++) {
if (e.getSource() == checkboxes[i]) {
suspended[i] = !suspended[i];
outputs[i].setBackground(
!suspended[i] ? Color.green : Color.red);
if (!suspended[i]) {
notify();
return;
Thanks in advance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Abiel wrote:
No, notifyAll() is used to tell the threads that we're stopping.... see that it's written in the stop() method of the applet. Eg if the user browses away from our applet we set the array of threads to null and notify them all. So notifyAll() makes sense.Yes, it does make sense there too (!!!!!!!).
However, I gave it a try with what u suggested, and it didn't work (as expected) .... Apparently you did not really read my suggestion or my explanation. If you had, you'd have expected it to work and it would have worked.
the problems still remains, some threads are getting in wait state even if their check box is not suspended.Maybe you should add the following code to understand the root cause and solution.
    System.out.println("Thread " + index + " will wait to be notified.");
    wait();
    System.out.println("Thread " + index + " was notified.");
what could the problem be?Improper use of notify()
With kind regards
Ben

Similar Messages

  • Deitel, Java How To Program exercise question

    Hi, :)
    I'm new to programming and I'm using the Java How To Program Fourth Edition from Deitel and Deitel as my text. I've run into a problem with Exercise 2.16 Where I'm asked:
    "Write an application that asks the user to enter two numbers, obtains the numbers from the user and prints the sum, product, difference, and quotient of the numbers."
    From that I have written this code:
    // Exercise 2.16
    /* An application that asks the user to enter two numbers, obtains the numbers from the use and prints the sum,
    product, difference and quotient of the numbers. Using the techniques shown in Fig 2.9 */
    //Java extension packages
    import javax.swing.JOptionPane;
    public class Exercise2_16{
         //Main method
         public static void main(String args[]){
         String firstNumber, secondNumber;                          //introduce variables
         int number1, number2, sum, product, difference, quotient;          //introduce variables
         firstNumber=JOptionPane.showInputDialog("Enter first integer:");     //Create input window
         secondNumber=JOptionPane.showInputDialog("Enter second integer:");     //Create input window
         number1=Integer.parseInt(firstNumber);                         //String to integer
         number2=Integer.parseInt(secondNumber);                         //String to integer
         //perform operations
         sum = number1+number2;
         product = number1*number2;
         difference = number1-number2;
         quotient = number1/number2;
         //Display results
         JOptionPane.showMessageDialog(null, "The sum is " + sum,
         "The product is " + product, "The difference is " + difference,
         "The quotient is " + quotient, "Results", JOptionPane.INFORMATION_MESSAGE);
         //End program
         System.exit(0);
         }//End main method
    }//end class Exercise2_16
    When I compile this code I get an error and I can't figure out why. Any help is really appreciated as I'm stumped and given the simplicity of the app I'm kinda bummed it has me stuck :(.

    I substituted your line and this is the error I'm receiving now:
    F:\jdk1.3\Learning Java>javac Exercise2_16.java
    Exercise2_16.java:32: unclosed string literal
    JOptionPane.showMessageDialog(null, "The sum is " + sum + ", The product is" + product + ",
    The difference is" + difference + ", The quotient is" + quotient + ", \"Results\", JOptionPane.INFORMATION_MESSAGE);
    ^
    Exercise2_16.java:35: ')' expected
    System.exit(0);
    ^
    2 errors
    It doesn't really matter to me if there are returns but maybe for readability there should be and so I learn how to as well.

  • Exercises in Java How To Program Sixth Edition

    Would anyone happen to have the following exercises 2.26, 2.28, 2.29, 2.30, 2.31, 3.8, 3.9, 3.11, 3.12, 3.13, 3.14, 3.15.... and if so.. would you mind sharing.. please let me know!
    g'day :D

    God.. fine than i'll post my code..i am dedicated.. just tired..
    * Main.java
    * Created on January 14, 2006, 9:58 PM
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    package javaapplication4;
    import java.util.Scanner;
    * @author user
    public class Main {
    /** Creates a new instance of Main */
    public Main() {
    * @param args the command line arguments
    public static void main(String[] args) {
    Scanner input = new Scanner ( System.in );
    int userinput;
    System.out.print("Enter five digit number: ");
    userinput = input.nextInt();
    System.out.printf(" %d ", (userinput % 10));
    userinput = userinput / 10;
    System.out.printf(" %d ", (userinput % 10));
    userinput = userinput / 10;
    System.out.printf(" %d ", (userinput % 10));
    userinput = userinput / 10;
    System.out.printf(" %d ", (userinput % 10));
    userinput = userinput / 10;
    System.out.printf(" %d ", (userinput % 10));
    what i want it to do.. say you enter 12345 ... it comes back and returns
    5 4 3 2 1 ...
    how do you reverse this proces...??

  • How to program in java

    hey guys. i am an undergraduate student. graduating next spring 2007. i did all my programming languages which were required in my course in 2004 and since that i have not taken any programming classes. i got my internship as a database administrator so got into MSaccess and Sql and VbA scripting. since my graduation year is near i want to be strong in database and programming and i was just reading about the employers what kind of programming they prefer and most of the times out of 100 you can say 80% needs java. so i have realized if i have my skills good in java and database job wont be any problem. i would like you to tell me about books i can buy from amazon.com or resources on internet from which i can understand the concept of programming again and then once my concept is clear about all the data types and functions i can start learning java. i would like you to tell me good java books also and some advance. the only book i have is the second edition of Java how to program. Thanks alot for all your help.

    The perverbial List:
    Free Tutorials and Such
    Installation Notes - JDK 5.0 Microsoft Windows (32-bit)
    Your First Cup of Java
    The Java� Tutorial - A practical guide for programmers
    New to Java Center
    Java Programming Notes - Fred Swartz
    How To Think Like A Computer Scientist
    Introduction to Computer science using Java
    The Java Developers Almanac 1.4
    Object-Oriented Programming Concepts
    Object-oriented language basics
    Don't Fear the OOP
    Free Java Books
    Thinking in Java, by Bruce Eckel (Free online)
    Core Servlet Programming, by Merty Hall (Free Online)
    More Servlets, by Marty Hall (Free Online)
    A Java GUI Programmer's Primer
    Data Structures and Algorithms
    with Object-Oriented Design Patterns in Java, by Bruno R. Preiss
    Introduction to Programming Using Java, by David J. Eck
    Advanced Programming for the Java 2 Platform
    The Java Language Specification
    Books:
    Head First Java, by Bert Bates and Kathy Sierra
    Core Java, by Cay Horstmann and Gary Cornell
    Effective Java, by Joshua Bloch
    Enjoy
    JJ

  • Modify the TicTacToeServer /client from deitel How to program

    We've been given example code from the deitel & deitel book how to program and have to carry out the following alterations:
    a) Modify the TicTacToeServer class to test for a win, loss or draw on each move in the game. Send a message to each client applet that indicates the result of the game when the game is over.
    b) Modify the TicTacToeClient class to display a button that when clicked allows the client to play another game. The button should be enabled only when a game completes. Note that both class TicTacToeClient and class TicTacToeServer must be modified to reset the board and all state information. Also, the other TicTacToeClient should be notified that a new game is about to begin so its board and state can be reset.
    c) Modify the TicTacToeClient class to provide a button that allows a client to terminate the program at any time. When the user clicks the button, the server and the other client should be notified. The server should then wait for a connection from another client so a new game can begin.
    d) Modify the TicTacToeClient class and the TicTacToeServer class so the winner of a game can choose game piece X or O for the next game. Remember: X always goes first.
    So far I have only been able to do part a) of the exercise im having a lot of difficulty with part b) which allows the client to play a new game.The code ive done so far is listed below if anyone can help i would be forever greatful. Thanks
    // Fig. 18.9: TicTacToeClient.java
    // Client that let a user play Tic-Tac-Toe with another across a network.
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    public class TicTacToeClient extends JApplet implements Runnable, ActionListener {
    private JButton Button;
    private JTextField idField;
    private JTextArea displayArea;
    private JPanel boardPanel, panel2;
    private Square board[][], currentSquare;
    private Socket connection;
    private DataInputStream input;
    private DataOutputStream output;
    private char myMark;
    private boolean myTurn;
    private final char X_MARK = 'X', O_MARK = 'O';
    boolean done=false;
    Container container;
    // Set up user-interface and board
    public void init()
    container = getContentPane();
    // set up JTextArea to display messages to user
    displayArea = new JTextArea( 4, 30 );
    displayArea.setEditable( false );
    container.add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
    // set up panel for squares in board
    boardPanel = new JPanel();
    boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
    // create board
    board = new Square[ 3 ][ 3 ];
    // When creating a Square, the location argument to the constructor
    // is a value from 0 to 8 indicating the position of the Square on
    // the board. Values 0, 1, and 2 are the first row, values 3, 4,
    // and 5 are the second row. Values 6, 7, and 8 are the third row.
    for ( int row = 0; row < board.length; row++ ) {
    for ( int column = 0; column < board[ row ].length; column++ ) {
    // create Square
    board[ row ][ column ] = new Square( ' ', row * 3 + column );
    boardPanel.add( board[ row ][ column ] );
    // textfield to display player's mark
    idField = new JTextField();
    idField.setEditable( false );
    container.add( idField, BorderLayout.NORTH );
    Button = new JButton("New Game");
    container.add(Button, BorderLayout.BEFORE_FIRST_LINE);
    // set up panel to contain boardPanel (for layout purposes)
    panel2 = new JPanel();
    panel2.add( boardPanel, BorderLayout.CENTER );
    container.add( panel2, BorderLayout.CENTER );
    } // end method init
    // Make connection to server and get associated streams.
    // Start separate thread to allow this applet to
    // continually update its output in textarea display.
    public void start()
    // connect to server, get streams and start outputThread
    try {
    // make connection
    connection = new Socket( getCodeBase().getHost(), 12345 );
    // get streams
    input = new DataInputStream( connection.getInputStream() );
    output = new DataOutputStream( connection.getOutputStream() );
    // catch problems setting up connection and streams
    catch ( IOException ioException ) {
    ioException.printStackTrace();
    // create and start output thread
    Thread outputThread = new Thread( this );
    outputThread.start();
    } // end method start
    // control thread that allows continuous update of displayArea
    public void run()
    // get player's mark (X or O)
    try {
    myMark = input.readChar();
    // display player ID in event-dispatch thread
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run()
    idField.setText( "You are player \"" + myMark + "\"" );
    myTurn = ( myMark == X_MARK ? true : false );
    // receive messages sent to client and output them
    while ( !done) {
    processMessage( input.readUTF() );
    } // end try
    // process problems communicating with server
    catch ( IOException ioException ) {
    ioException.printStackTrace();
    } // end method run
    // process messages received by client
    private void processMessage( String message )
    // valid move occurred
    if ( message.equals( "Valid move." ) ) {
    displayMessage( "Valid move, please wait.\n" );
    setMark( currentSquare, myMark );
    // invalid move occurred
    else if ( message.equals( "Invalid move, try again" ) ) {
    displayMessage( message + "\n" );
    myTurn = true;
    // opponent moved
    else if ( message.equals( "Opponent moved" ) ) {
    // get move location and update board
    try {
    int location = input.readInt();
    int row = location / 3;
    int column = location % 3;
    setMark( board[ row ][ column ],
    ( myMark == X_MARK ? O_MARK : X_MARK ) );
    displayMessage( "Opponent moved. Your turn.\n" );
    myTurn = true;
    } // end try
    // process problems communicating with server
    catch ( IOException ioException ) {
    ioException.printStackTrace();
    } // end else if
    else if ( message.equals("Game Over") ){
    displayMessage("fuck sake" );
    // simply display message
    else
    displayMessage( message + "\n" );
    } // end method processMessage
    // utility method called from other threads to manipulate
    // outputArea in the event-dispatch thread
    private void displayMessage( final String messageToDisplay )
    // display message from event-dispatch thread of execution
    SwingUtilities.invokeLater(
    new Runnable() {  // inner class to ensure GUI updates properly
    public void run() // updates displayArea
    displayArea.append( messageToDisplay );
    displayArea.setCaretPosition(
    displayArea.getText().length() );
    } // end inner class
    ); // end call to SwingUtilities.invokeLater
    // utility method to set mark on board in event-dispatch thread
    private void setMark( final Square squareToMark, final char mark )
    SwingUtilities.invokeLater(
    new Runnable() {
    public void run()
    squareToMark.setMark( mark );
    // send message to server indicating clicked square
    public void sendClickedSquare( int location )
    if ( myTurn ) {
    // send location to server
    try {
    output.writeInt( location );
    myTurn = false;
    // process problems communicating with server
    catch ( IOException ioException ) {
    ioException.printStackTrace();
    // set current Square
    public void setCurrentSquare( Square square )
    currentSquare = square;
    public void actionPerformed(ActionEvent e) {
    // I need code here
    // private inner class for the squares on the board
    private class Square extends JPanel {
    private char mark;
    private int location;
    public Square( char squareMark, int squareLocation )
    mark = squareMark;
    location = squareLocation;
    addMouseListener(
    new MouseAdapter() {
    public void mouseReleased( MouseEvent e )
    setCurrentSquare( Square.this );
    sendClickedSquare( getSquareLocation() );
    } // end Square constructor
    // return preferred size of Square
    public Dimension getPreferredSize()
    return new Dimension( 30, 30 );
    // return minimum size of Square
    public Dimension getMinimumSize()
    return getPreferredSize();
    // set mark for Square
    public void setMark( char newMark )
    mark = newMark;
    repaint();
    // return Square location
    public int getSquareLocation()
    return location;
    // draw Square
    public void paintComponent( Graphics g )
    super.paintComponent( g );
    g.drawRect( 0, 0, 29, 29 );
    g.drawString( String.valueOf( mark ), 11, 20 );
    } // end inner-class Square
    } // end class TicTacToeClient
    // Fig. 18.8: TicTacToeServer.java
    // This class maintains a game of Tic-Tac-Toe for two client applets.
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    public class TicTacToeServer extends JFrame {
    private char[] board;
    private JTextArea outputArea;
    private Player[] players;
    private ServerSocket server;
    private int currentPlayer;
    private final int PLAYER_X = 0, PLAYER_O = 1;
    private final char X_MARK = 'X', O_MARK = 'O';
    int moves=0;
    // set up tic-tac-toe server and GUI that displays messages
    public TicTacToeServer()
    super( "Tic-Tac-Toe Server" );
    board = new char[ 9 ];
    for (int i = 0; i<9; i++){
    board[i] = ' ';
    players = new Player[ 2 ];
    currentPlayer = PLAYER_X;
    // set up ServerSocket
    try {
    server = new ServerSocket( 12345, 2 );
    // process problems creating ServerSocket
    catch( IOException ioException ) {
    ioException.printStackTrace();
    System.exit( 1 );
    // set up JTextArea to display messages during execution
    outputArea = new JTextArea();
    getContentPane().add( outputArea, BorderLayout.CENTER );
    outputArea.setText( "Server awaiting connections\n" );
    setSize( 300, 300 );
    setVisible( true );
    } // end TicTacToeServer constructor
    // wait for two connections so game can be played
    public void execute()
    // wait for each client to connect
    for ( int i = 0; i < players.length; i++ ) {
    // wait for connection, create Player, start thread
    try {
    players[ i ] = new Player( server.accept(), i );
    players[ i ].start();
    // process problems receiving connection from client
    catch( IOException ioException ) {
    ioException.printStackTrace();
    System.exit( 1 );
    // Player X is suspended until Player O connects.
    // Resume player X now.
    synchronized ( players[ PLAYER_X ] ) {
    players[ PLAYER_X ].setSuspended( false );
    players[ PLAYER_X ].notify();
    } // end method execute
    // utility method called from other threads to manipulate
    // outputArea in the event-dispatch thread
    private void displayMessage( final String messageToDisplay )
    // display message from event-dispatch thread of execution
    SwingUtilities.invokeLater(
    new Runnable() {  // inner class to ensure GUI updates properly
    public void run() // updates outputArea
    outputArea.append( messageToDisplay );
    outputArea.setCaretPosition(
    outputArea.getText().length() );
    } // end inner class
    ); // end call to SwingUtilities.invokeLater
    // Determine if a move is valid. This method is synchronized because
    // only one move can be made at a time.
    public synchronized boolean validateAndMove( int location, int player )
    boolean moveDone = false;
    // while not current player, must wait for turn
    while ( player != currentPlayer ) {
    // wait for turn
    try {
    wait();
    // catch wait interruptions
    catch( InterruptedException interruptedException ) {
    interruptedException.printStackTrace();
    // if location not occupied, make move
    if ( !isOccupied( location ) ) {
    // set move in board array
    board[ location ] = currentPlayer == PLAYER_X ? X_MARK : O_MARK;
    // change current player
    currentPlayer = ( currentPlayer + 1 ) % 2;
    // let new current player know that move occurred
    players[ currentPlayer ].otherPlayerMoved( location );
    notify(); // tell waiting player to continue
    // tell player that made move that the move was valid
    return true;
    // tell player that made move that the move was not valid
    else
    return false;
    } // end method validateAndMove
    // determine whether location is occupied
    public boolean isOccupied( int location )
    if ( board[ location ] == X_MARK || board [ location ] == O_MARK )
    return true;
    else
    return false;
    void gameOverCheck() {
    boolean over = false;
    // Check rows
    for (int start=0; start < 9; start += 3)
    over = over || ((board[start] != ' ') &&
    (board[start] == board[start+1]) &&
    (board[start] == board[start+2]));
    // Check columns
    for (int start=0; start < 3; start++)
    over = over || ((board[start] != ' ') &&
    (board[start] == board[start+3]) &&
    (board[start] == board[start+6]));
    // Check diagonals
    over = over || ((board[0] != ' ') &&
    (board[0] == board[4]) && (board[0] == board[8]));
    over = over || ((board[2] != ' ') &&
    (board[2] == board[4]) && (board[2] == board[6]));
    if (over || (moves>=9))
    for ( int i = 0; i < players.length; i++ )
    players.gameOver(over ? (currentPlayer+1)%2 : -1 );
    public static void main( String args[] )
    TicTacToeServer application = new TicTacToeServer();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    application.execute();
    // private inner class Player manages each Player as a thread
    private class Player extends Thread {
    private Socket connection;
    private DataInputStream input;
    private DataOutputStream output;
    private int playerNumber;
    private char mark;
    protected boolean suspended = true;
    boolean done = false;
    // set up Player thread
    public Player( Socket socket, int number )
    playerNumber = number;
    // specify player's mark
    mark = ( playerNumber == PLAYER_X ? X_MARK : O_MARK );
    connection = socket;
    // obtain streams from Socket
    try {
    input = new DataInputStream( connection.getInputStream() );
    output = new DataOutputStream( connection.getOutputStream() );
    // process problems getting streams
    catch( IOException ioException ) {
    ioException.printStackTrace();
    System.exit( 1 );
    } // end Player constructor
    // send message that other player moved
    public void otherPlayerMoved( int location )
    // send message indicating move
    try {
    output.writeUTF( "Opponent moved" );
    output.writeInt( location );
    // process problems sending message
    catch ( IOException ioException ) {
    ioException.printStackTrace();
    void gameOver(int winner) {
    try {
    output.writeUTF( "Game Over. " +
    (( winner == -1 ) ? "No winner." :
    ( "Winner is " + ( winner == 0 ? 'X' : 'O' ) + "." ) ) );
    done=true;
    output.writeUTF("Game Over");
    } catch( IOException e ) {
    e.printStackTrace(); System.exit( 1 );
    public void run()
    // send client message indicating its mark (X or O),
    // process messages from client
    try {
    displayMessage( "Player " + ( playerNumber ==
    PLAYER_X ? X_MARK : O_MARK ) + " connected\n" );
    output.writeChar( mark ); // send player's mark
    // send message indicating connection
    output.writeUTF( "Player " + ( playerNumber == PLAYER_X ?
    "X connected\n" : "O connected, please wait\n" ) );
    // if player X, wait for another player to arrive
    if ( mark == X_MARK ) {
    output.writeUTF( "Waiting for another player" );
    // wait for player O
    try {
    synchronized( this ) {
    while ( suspended )
    wait();
    // process interruptions while waiting
    catch ( InterruptedException exception ) {
    exception.printStackTrace();
    // send message that other player connected and
    // player X can make a move
    output.writeUTF( "Other player connected. Your move." );
    while ( ! done ) {
    // get move location from client
    int location = input.readInt();
    // check for valid move
    if ( validateAndMove( location, playerNumber ) ) {
    displayMessage( "\nlocation: " + location );
    output.writeUTF( "Valid move." );
    gameOverCheck();
    else
    output.writeUTF( "Invalid move, try again" );
    // close connection to client
    } // end try
    // process problems communicating with client
    catch( IOException ioException ) {
    ioException.printStackTrace();
    System.exit( 1 );
    // end method run
    // set whether or not thread is suspended
    public void setSuspended( boolean status )
    suspended = status;
    } // end class Player
    } // end class TicTacToeServer

    reply #1:
    http://forum.java.sun.com/thread.jspa?threadID=5114663
    &tstart=0@Op. Don't multi/cross-post

  • How to find out top 10 records from the R/3 using Java code (WD Program)

    Hi Experts,
    I have used Java Web Dynpro program to fetch records from the backend. Following code helps me and fetches record. As per the customer reqirement, we have to fetch only top 10 records (Actual Cost) from the backend. So I have to modify the Java code. How I can do so? Please help.
              wdContext.nodeGraphData().invalidate();
              IPublicCostcnt.IGraphDataElement categoryElement;
                   for (int i = 0; i < wdContext.nodeItab_Final1().size(); i++) {
                   categoryElement = wdContext.createGraphDataElement();
                   categoryElement.setCostElement(""+ wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getDescription());
                   categoryElement.setActualCost(wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getActual_Cost().toString());
                   categoryElement.setPlannedCost(wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getPlan_Cost().toString());
                   wdContext.nodeGraphData().addElement(categoryElement);
    Regards,
    Gary

    Dear SDN Users,
    This is how I resolved the issue.
    1) Requested ABAPer to provide me sorted data. The data has been sorted in descending order of actual_cost.
    2) After that I used following code. This resolved the issue.
         if (wdContext.nodeItab_Final1().size()>10){
         IPublicCostcnt.IGraphDataElement categoryElement;
              for (int i = 0; i < 10; i++) {
              categoryElement = wdContext.createGraphDataElement();
              categoryElement.setCostElement(""+ wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getDescription());
              categoryElement.setActualCost(wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getActual_Cost().toString());
              categoryElement.setPlannedCost(wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getPlan_Cost().toString());
              wdContext.nodeGraphData().addElement(categoryElement);
         if (wdContext.nodeItab_Final1().size()<=10){
         if (wdContext.nodeItab_Final1().size()>0){
         IPublicCostcnt.IGraphDataElement categoryElement;
              for (int i = 0; i < wdContext.nodeItab_Final1().size(); i++) {
              categoryElement = wdContext.createGraphDataElement();
              categoryElement.setCostElement(""+ wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getDescription());
              categoryElement.setActualCost(wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getActual_Cost().toString());
              categoryElement.setPlannedCost(wdContext.nodeItab_Final1().getItab_Final1ElementAt(i).getPlan_Cost().toString());
              wdContext.nodeGraphData().addElement(categoryElement);
    Regards,
    Gary

  • Im trying to download an update to my ipad of bug fixing but dont kno how

    How can i fix my ipad or how can i download a bug fixer

    I know of no bug fixer for iOS.
    How about if you describe the problems you are havinhg with your iPad.
    Allan

  • ( im new to java) How do I increase number of columns in a JTable ?

    I am dooing a small calculating program in school and can't figure out how to change the amount of columns in a JTable, my programming skills sofar are extremely basic and therefore we are using the netbeans GUI to create our windows. The code generated by the GUI cannot be edited and I have tried to copy paste the code into Eclipse but it didn't work.
    I have a fair idea of where in the code you can preform the things I want but I need to do it in the grapical interface.
    any suggestions are very much appriciated.

    my programming skills sofar are extremely basic and therefore we are using the netbeans GUI to create our windows.Using and IDE doesn't not make it easier. As you've found out it only makes it harder since you can't edit the code and take full control.
    Read the Swing tutorial, it contains plenty of example for building GUI applications:
    http://java.sun.com/docs/books/tutorial/uiswing/TOC.html
    I don't really understand your question, because if you create the table correctly, then then is no need to increase the number of columns. However, the table does support an addColumn(....) method.

  • I know how to program in java(Should I learn c, c++?)

    I know how to program in java. I want to be able to communicate with the hardware on my pc. I also hear that C, C++ is a lower level than java. Lower level meaning it can communicate with the hardware. I know java is very portable could do interfacing and could do so many things with the java programming language. I find the java programmig language cool. Now when I read about the JNI(java native interface) I think I could communicate with methods from java to functions in c++. I want to learn c++ and use it with JNI.
    Posting this topic because I want to be sure about what I'm doing.
    Thanks
    George

    in fact, memory management is the main pitfall in C++ programming. The following may give you a few headaches:
    - destructors
    - header files which try to include eachother
    - "memory access violation"
    - templates (upcoming java includes generics, which is similar)
    - pointers
    If you can overcome the above problems, you'll find that c++ is much like Java, only a bit more low-level. Accessing hardware directly however is quite a challenge (espescially under Windows which doesn't allow direct access for as far as I know), but not impossible. I don't know exactly, but I think it involves developing a small driver layer.
    It's to bad you learnt Java before C++, the other way around would have been much easier.

  • How to program in Java to delete a ZipEntry in ZipFile

    As we all known we can delete a zipentry in zipfile easily using WinZip,but how to program in Java to delete a ZipEntry in ZipFile? I can not find API function in ZIP package.Please help me,thanks.

    I think there are no methods to delete a particual file from a zip file -
    maybe there are packagers for that but not in java.util.zip
    you can just write your own function uncompress - and create a new file again - you can look here to get some examples
    http://www.idevelopment.info/data/Programming/java/zip/

  • How to implement node affinity for java type concurrent programs.

    How to run a concurrent program against a specific RAC instance with PCP/RAC setup? (Doc ID 1129203.1)
    This works for non java registered concurrent programs but not java registered with use the DBC file
    EBS RAC environment with two RAC nodes. We would like to implement node affinity to allow concurrent programs to be directed to a single RAC instance. Oracle have provided the NODE AFFINITY ability via the concurrent program definition in Session Control. This then uses the entry in the 10.1.2 tnsnames.ora to pass the request directly through to the instance as defined by Node Affinity.
    However, concurrent programs defined as type java do not access the database by the 10.1.2 tnsnames.ora but use the dbc file under $FND_SECURE. This file is configured for both self service and concurrent processing so any change to the dbc file entry will affect both self service and concurrent processing.
    How to we implement a node affinity solution for concurrent programs without affecting Self Service conncetions? We'd like the dbc file to directly connect java concurrernt programs through to one instance but the self service connections to use the SERVICE name only.
    Regards.
    philippe.

    Did you think about Online/Batch node concept ? By that way you can seggrecate application connection.

  • How to program this in java? Please help

    How to program this in java?
    please explain steps, it has to come out like this:
    example
    input: 3b1w3b
    output:
    BBBWBBB

    import java.io.*;
    public class Test {
    static java.io.PrintStream o = java.lang.System.out;
    public static void main(String[] args)throws Exception {      
         BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
         System.out.print("Enter plot for printing: ");
         String s = BR.readLine();
         char[] cs = s.toLowerCase().toCharArray();
         for(int i=0, j=0; i < cs.length-0x1; i+=0x2, j=0)
              while(j++ < (int)(cs[i]-0x30))
                   o.print((char)(cs[i+0x1]-0x20));
    I tried changeing it to this so I can enter my own string, but I want to change it some more so that it can enter multiple input separated by space, so that it can form a sort of picture line by line. I tried using tolkenizer but I get errors. I dont know how to use tolkenizer properly can anyone please TEACH. you dont have to tell how or give me the code if you dont want to. yes I know Im a noob and I dont know java as good as everyone here, If everyone thinks I don't deserve help then DON'T help, I'm just trying to learn programming

  • How to program a screensaver with java???

    Hi all,
    Can someone tell em how to program a screensaver with java, and how should i begin ? or maybe someone know any useful information source?
    thanks a lot.
    ck

    A quick google search gives me, among lots of other things:
    http://kevinkelley.mystarband.net/java/sava.html
    Good luck
    Lee

  • I want to do rpc programming through java how can i do it?

    i want to do rpc programming through java how can i do it? any classes for it? i am not goin to use rmi its an assignment for us in syllabe help is strongly needed

    So, you are in a class. You are a student, your job is to learn something. Unless your instructor has failed horribly in his/her duty, then you are failing in your duty as a student.
    Your lack of even trying hurts me personally as a life-long student, I find your post ill-advised.
    Please, do not post to these forums anymore. Thank you.

  • Handling exception logging in a Java task scheduler program?

    I need to design a Task Scheduler Where
    1) User should be able to schedule multiple task at the same time.
    2) There should be proper error handling on failure of any task and should not affect the other running tasks.
    I found the related programme at http://www.roseindia.net/java/example/java/util/CertainAndRepeatTime.shtml
    My concern is about handling of point 2 in program provided at above link. Say I schedule a recurring mail send process in above program which will be run first time on 12 september 2011 at 2 am, and will be repeated after every 2 hours Say a one process fais at 8 am. I want to log it in log file with task name and time details. Now if I look at above programme i.e CertainAndRepeatTime.java. This program will exit once it schedules all the tasks. Where and how should handle the logging?
    Posted at http://stackoverflow.com/questions/7377204/handling-exception-logging-in-a-java-task-scheduler-program but folks suggesting Quartz scheduler . My Limitation is that i can't for quartz because my project allows me to use only standard java library. Is there any way we can handle logging in the same programme in case of exception.

    Well, first of all I wouldn't trust any code from roseindia. So you might want to look for more reliable advice.
    As for your logging, you can add it for example to the TimerTask itself. I don't recommend adding logging to that roseindia cr*p though.

Maybe you are looking for