Is there an equivalent SELECT() method in Java for passive-waiting?

I have been using C code that will open a file descriptor, then use the "select" function to passively-wait for new events in the descriptor (versus something like an active while-loop strategy that will loop indefinitely, attempting to read from the descriptor each time through the loop).
Can someone describe the best way of migrating this C code to Java? I am particularly interested in finding out how to duplicate the "select" behavior in Java.
Thanks for your help.
-TJW
Here is part of the C code as it currently stands:
#define PS2_DEVICE "/dev/psaux"
/* the descriptor */
int fd_ps2;
if ((fd_ps2 = open(PS2_DEVICE, O_RDWR | O_SYNC | O_NDELAY)) == -1 )
perror("Error opening PS2 port.");
exit(-1);
int ret;
/* an array of file descriptors */
fd_set fds;
/* a structure to hold select time-out information */
struct timeval tv;
/* the acknowledgement byte */
unsigned char ack_byte = -2;
/* attempt to send the byte, i.e. write to the file descriptor */
if (write(fd, &snd_byte, 1) != SUCCESS) {
perror("Error sending the byte.");
return ERROR;
/* clear the file descriptor set */
FD_ZERO(&fds);
/* add the desired descriptor(s) to the set. In our case, we are only
* concerned with the psaux descriptor */
FD_SET(fd, &fds);
/* set the time structure's time values that will be used to enforce
* time-outs for the select */
tv.tv_sec = 0; // seconds
tv.tv_usec = 200; // milli-seconds
/* wait on the file descriptor for communication
* to the host */
ret = select(fd + 1, &fds, 0, 0, &tv);
/* ret should contain the number of descriptors contained in the
* descriptor set, which may be zero if the timeout expires before
* anything interesting happens */
if (ret == -1) {
puts("Select error.");
return ERROR;
else if (ret == 0) {
puts("Timed out.");
return ERROR;
else if (ret > 0) {
/* there is at least one descriptor still in the set */
else {
/* some other error occurred */
return ERROR;
if (read(fd, (void *)&ack_byte, 1) != SUCCESS) {
puts("Error reading from the descriptor.");
return ERROR;
.........

Hi TJW,
Assuming you haven't already read it, perhaps this article will help:
http://www.developer.com/net/net/article.php/626271
Hope it helps you.
Good Luck,
Avi.

Similar Messages

  • Is there a "Drag-Select" Method?

    I remember many years ago when Aldus PageMaker was popular. In that program I was able to script and perform a "drag-select" in a specific area of choice.
    Can anyone describe or offer any ideas on how to go about this using Applescript or with Javascript?
    (Ps: I only understand applescript, but lets have fun and discover new ways to do something new and learn at the same time!)
    Thank you everyone...

    This will let you act on all items whose top left fall within a range of coordinates; you could easily modify it to deal with items contained by the ranges:
    tell application "Adobe InDesign CS3"
    tell document 1
    <do something to> (every item of all page items of page 1 where item 1 of its geometric bounds is greater than 72 and item 1 of its geometric bounds is less than 400 and item 2 of its geometric bounds is greater than 72 and item 2 of its geometric bounds is less than 500)
    end tell
    end tell
    Shane Stanley <[email protected]>
    AppleScript Pro Sessions <http://scriptingmatters.com/aspro>

  • Is installing Java for OS X 2014-001 safe?

    Is there any reason to install Java for OS X 2014-001 posted 05-29-2014?
    Is there any reason not  to install Java for OS X 2014-001 posted 05-29-2014?
    Will this download remove/replace or overwrite my Java 7 install?
    (Java for OS X 2014-001 includes installation improvements, and supersedes all previous versions of Java for OS X. This package installs the same version of Java 6 included in Java for OS X 2013-005. Please quit any Java applications before installing this update)
    See the following KB articles;
    http://support.apple.com/kb/HT6133
    http://support.apple.com/kb/HT1222

    What FOLLOWING paragraph?
    The statement in parentheses say is "all previous versions of Java for OS X". In my understanding of the word previous, it does not mean replacing anything newer, such as version JAVA7 which is newer than version 6.

  • Is there an equivalent statement in Java for this PL/SQL stmt?

    Hi,
    I want to know if there is an equivalent statement
    in java for this PL/SQL statement:
    IF strTok IN('COM-1','COM-2','COM-3') Then
    /* Do Something */
    End If;
    I tried using : // This is giving me errors..
    if (strTok.equals(("COM-1") || ("COM-2") || ("COM-3") ) )
    /* Do Something */
    The above Java code is giving me errors.
    Any Help to reduce the number of steps for comparison
    is appreciated.
    thanks in adv
    Sharath

    Something like
    if (strTok.equals("COM-1") ||
        strTok.equals("COM-2") ||
        strTok.equals("COM-3") )Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Java.nio select() method return 0 in my client application

    Hello,
    I'm developing a simple chat application who echo messages
    But my client application loop because the select() method return 0
    This is my code
    // SERVER
    package test;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    public class Server {
         private int port = 5001;
         public void work() {               
              try {
                   ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                   serverSocketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(port);               
                   serverSocketChannel.socket().bind(isa);
                   Selector selector = Selector.open();
                   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                   System.out.println("Listing on "+port);
                   while(selector.select()>0) {
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isAcceptable()) {
                                  ServerSocketChannel keyChannel = (ServerSocketChannel)key.channel();                              
                                  SocketChannel channel = keyChannel.accept();
                                  channel.configureBlocking(false);                              
                                  channel.register(selector, SelectionKey.OP_READ );
                             } else if (key.isReadable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel );
                                  Help.write(m.toUpperCase(), keyChannel );
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         public static void main(String[] args) {
              Server s = new Server();
              s.work();
    // CLIENT
    package test;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {               
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);               
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   socketChannel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ );
                   while(true) {
                        selector.select();
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();) {
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable()) {
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  if (keyChannel.isConnectionPending()) {
                                       System.out.println("Connected "+keyChannel.finishConnect());                                                                           
                             } else if (key.isReadable()) {                                                                                                                                                           
                                  SocketChannel keyChannel = (SocketChannel) key.channel();                                             
                                  String m = Help.read(keyChannel);
                                  display(m);                                                                                                                                                                                                                   
              } catch (IOException e) {                                             
                   e.printStackTrace();                         
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {               
                   public void run() {                                                                                
                        try {                         
                             Help.write(m, socketChannel);
                        } catch (IOException e) {               
                             e.printStackTrace();
              t.start();                    
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);     
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();
    // HELPER CLASS
    package test;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.nio.charset.CharsetEncoder;
    public class Help {
         private static Charset charset = Charset.forName("us-ascii");
         private static CharsetEncoder enc = charset.newEncoder();
         private static CharsetDecoder dec = charset.newDecoder();
         private static void log(String m) {
              System.out.println(m);
         public static String read(SocketChannel channel) throws IOException {
              log("*** start READ");                              
              int n;
              ByteBuffer buffer = ByteBuffer.allocate(1024);
              while((n = channel.read(buffer)) > 0) {
                   System.out.println("     adding "+n+" bytes");
              log("  BUFFER REMPLI : "+buffer);
              buffer.flip();               
              CharBuffer cb = dec.decode(buffer);          
              log("  CHARBUFFER : "+cb);
              String m = cb.toString();
              log("  MESSAGE : "+m);          
              log("*** end READ");
              //buffer.clear();
              return m;                    
         public static void write(String m, SocketChannel channel) throws IOException {          
              log("xxx start WRITE");          
              CharBuffer cb = CharBuffer.wrap(m);
              log("  CHARBUFFER : "+cb);          
              ByteBuffer  buffer = enc.encode(cb);
              log("  BUFFER ALLOUE REMPLI : "+buffer);
              int n;
              while(buffer.hasRemaining()) {
                   n = channel.write(buffer);                         
              System.out.println("  REMAINING : "+buffer.hasRemaining());
              log("xxx end WRITE");

    Here's the fix for that old problem. Change the work method to do the following
    - don't register interest in things that can't happen
    - when you connect register based on whether the connection is complete or pending.
    - add the OP_READ interest once the connection is complete.
    This doesn't fix all the other problems this code will have,
    eg.
    - what happens if a write is incomplete?
    - why does my code loop if I add OP_WRITE interest?
    - why does my interestOps or register method block?
    For code that answers all those questions see my obese post Taming the NIO Circus
    Here's the fixed up Client code
    // CLIENT
    package test
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class Client extends JFrame  {
         private String host = "localhost";
         private int port = 5001;
         private SocketChannel socketChannel;
         private Selector selector;
         public void work() {
              try {
                   socketChannel = SocketChannel.open();
                   socketChannel.configureBlocking(false);
                   InetSocketAddress isa = new InetSocketAddress(host, port);
                   socketChannel.connect(isa);
                   selector = Selector.open();
                   int interest = 0;
                   if(socketChannel.isConnected())interest = SelectionKey.OP_READ;
                   else if(socketChannel.isConnectionPending())interest = SelectionKey.OP_CONNECT;
                   socketChannel.register(selector, interest);
                   while(true)
                        int nn = selector.select();
                        System.out.println("nn="+nn);
                        Set keys = selector.selectedKeys();
                        for(Iterator i = keys.iterator(); i.hasNext();)
                             SelectionKey key = (SelectionKey) i.next();
                             i.remove();
                             if (key.isConnectable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  System.out.println("Connected "+keyChannel.finishConnect());
                                  key.interestOps(SelectionKey.OP_READ);
                             if (key.isReadable())
                                  SocketChannel keyChannel = (SocketChannel) key.channel();
                                  String m = Help.read(keyChannel);
                                  display(m);
              } catch (IOException e) {
                   e.printStackTrace();
         private void display(final String m) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        area.append(m+"\n");
                        textFieed.setText("");
         private void sendMessage(final String m) {
              Thread t = new Thread(new Runnable() {
                   public void run() {
                        try {
                             Help.write(m, socketChannel);
                        } catch (IOException e) {
                             e.printStackTrace();
              t.start();
         public Client() {
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(1);
              textFieed.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode()== KeyEvent.VK_ENTER) {
                             String m = textFieed.getText();
                             sendMessage(m);
              area.setEditable(false);
              getContentPane().add(textFieed, "North");
              getContentPane().add(new JScrollPane(area));
              setBounds(200, 200, 400, 300);
              show();
         private String messageToSend;
         private JTextArea area = new JTextArea();
         JTextField textFieed = new JTextField();
         public static void main(String[] args) {
              Client s = new Client();
              s.work();

  • Is there any method in Java to convert from system time to variant time?

    From MSDN:
    A variant time is stored as an 8-byte real value (double), representing a date between January 1, 100 and December 31, 9999, inclusive. The value 2.0 represents January 1, 1900; 3.0 represents January 2, 1900, and so on. Adding 1 to the value increments the date by a day. The fractional part of the value represents the time of day. Therefore, 2.5 represents noon on January 1, 1900; 3.25 represents 6:00 A.M. on January 2, 1900, and so on. Negative numbers represent dates prior to December 30, 1899.
    Is there any method in Java to do this or do I need to write it?

    do I need to write it?yes

  • Does anyone know if there is an equivalent to setFocusable in Java 1.3?

    Does anyone know if there is an equivalent to setFocusable in Java 1.3? My school computers have Java 1.3 (ridiculously outdated) and we don't have priveledges to install 1.4 or 1.5... and the sysadmins are too lazy to update the image ;).

    When I search with the following string I get a number of hits...
    setFocusable "1.3"

  • Is there a method in java that can schedule work??

    I'm working on a project and I need to start a program at a fixed time each day.
    E.g. every day at 03:00 AM!
    Is there such a method in java?? Or can somebody give me an
    example of how this can be done!
    Thank you in advance : )

    it really depends on whether you mean you want the operating system to start the "program" for you, or whether you want your own java program to spawn other tasks...
    Check the OS docs if it is the former, and use java.util.TimerTask for the latter

  • What is the equivalent selection in BI7? (Following BW 3.5 How to...Set up

    Hi,
    What is the equivalent selection in BI7? (Following BW 3.5 How to...Set up BW Statistics)
    I am trying to install BW statistics and all the good things that come with it for BI7. Following the instructions in a document that I was directed to on this site, in SBIW, I installed and replicated all the datasource in under “TCT” tree (Technical content)
    The instruction is for versions prior to BI7 and I had to make modifications as I go.
    Now, this instruction direct me to go to:
    rsa1, “Bi Content” (left) and then “InfoProviders by InfoAreas” and select all InfoProviders for the InfoAreas ”BW Statistics” and “BW Metadata” under the node “Technical Content”.
    1.
    In BI7, there is no ”BW Statistics” and “BW Metadata” infoareas under “Technical Content” if I follow the directions strictly.
    What is the equivalent of this in BI7?
    2.
    In the instructions, the author continues to collect these InfoAreas from under “Technical Content”:
    BW Data Slice
    BW Features characteristics
    BW Metadata
    BW Statistics
    In BI7, do we need exactly these? Or, now different? Should I just transfer all the infoareas under “Technical Content”? What is the disadvantage of collecting a ALL?
    Thanks

    Thanks for the link and i believe it will come in handing.
    Yet, it does not have the step by step installation information on page 46 of this link:
    https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/c8c4d794-0501-0010-a693-918a17e663cc
    Do you have the BI7 version of this link?
    Also, ssame stewise info is on page 4 of this:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/5401ab90-0201-0010-b394-99ffdb15235b   
    If you have the BI7 version of this link also, it will answer my question.
    Thanks

  • Search help for a field using a selection method which has a text table.

    Hello all,
    I am trying to create a search help for one of the fields in a structure say RFCDEST. Now for this i am giving the selection method as the DB table where all the RFCDEST are maintained. However there is a text table which is also comes up for this selection method and the description of the filed RFCDEST is in that text table and the description is not stored in the main table which i specified as the selection method.
    My query is that on F4 now all the rfc destinations are being shown however the description i am not able to show them because there is no field in the table specified in the selectionmethod which hold s the description but instead it is there in the text table, how can i fetch the description from there and display in the search help.
    Warm Regards,
    Naveen M

    look at search help FC_RFCDEST. that problem has already been solved with this search help.

  • Is there a equivalent of "Data Validation" function in Numbers?

    Hi, I think this question have been asked before in 2009. But there's no conclusive answer. I just imported a medium complexity xlsx sheet into Numbers, "data validation have been removed data retained" message appeared. Is there a equivalent function in Numbers? Or can we construct one? The reason this is important is when using the Macs we are ok and less likely to "fat finger" the data entry. However with a iPad and especially the iPhone, we are more likely to "fat finger" the data entry and therefore a scroll wheel or drop-down list function will help.
    If anyone has a helpful answer that will be great!
    Ken
    ===

    "Data Validation" as such is not supported in Numbers.
    Numbers '09 does support two means of restricting data choices to a pre-determined list of choices:
    Pop-up menu is a cell format that provides a pop-up list of choices from which a value may be selected. Value not on the menu cannot be inserted (except by changing the cell's format, then entering the values manually).
    Slider and Stepper are two more cell formats. Both provide a mechanism for inserting numeric values, with the minimum, maximum and increment values set in the cell format inspector.
    The numeric values set by the Slider or Stepper can be used, in a separate cell, to lookup a text value from a table of possible values.
    The Numbers for iOS feature set is a subset of the one available in Numbers '09. I don't know if Pop-up menus, Sliders or Steppers are supported in the iOS version,
    Regards,
    Barry

  • Many more selection methods!! Period!!

    Hi everyone, and especially you, the developers of Illustrator and other Adobe programs...:
    I work a lot in both 3ds Max and Illustrator, and I often find myself working with hundreds of thousand polygons. The selection tools are so cool in 3ds Max, and give me every option of selecting faces on a complex model... For instance - just naming SOME options available in 3ds Max:
    Rectangular selection.*
    Circular selection
    Fence selection (selection in perfect straight lines)
    Lasso Selection.*
    Paint selection (like a brush - everything within the stroke gets selected)
    Soft selection (Selection method using a tolerance setting, see reference picture: http://fanous.persiangig.com/egg/egg03.gif )
    Video examples of some different ways to select in 3ds Max: http://www.digitaltutors.com/store/video.php?detectqt=false&vid=1694
    .*Illustrator present
    Another thing I think is missing in Illustrator is the ability to "make selection from guides" - because, you already have the ability to make costume guides, but you can't make a selection out of them ( as far as I know?)
    There are soooo many tips and tricks you developers of Adobe products could "borrow" from 3ds Max... Fx. clicking on the scroll wheel on the mouse as the "Hand tool" instead of the "Space command" on the keyboard. In Indesign it is especially a pain in the ***, when you are in the middle of writing text, and just need to have a look further down on the page, then you get a double space in the text when clicking space. - Imagine how easy it would be with a click on the scroll button on the mouse instead?!
    Cheers!
    Martin

    the ONLY thing Illustrator need is a
    RECTANGULAR WINDOW SELECTION TOOL
    WINDOW SELECTION TOOL
    WINDOW SELECTION TOOL
    WINDOW SELECTION TOOLWINDOW SELECTION TOOLWINDOW SELECTION TOOLWINDOW SELECTION TOOLWINDOW SELECTION TOOL
    WINDOW SELECTION TOOL
    WINDOW SELECTION TOOLWINDOW SELECTION TOOL
    WINDOW SELECTION TOOLWINDOW SELECTION TOOL
    WINDOW SELECTION TOOLWINDOW SELECTION TOOL.............so that all the object which are INSIDE the selction are selected
    so that all the object which are INSIDE the selction are selected
    so that all the object which are INSIDE the selction are selected
    so that all the object which are INSIDE the selction are selected
    so that all the object which are INSIDE the selction are selected
    so that all the object which are INSIDE the selction are selected
    LIKE ALL THE OTHER, similar software
    ps: sorry for this typical layout, but I am Sooooo frustrated about this!

  • There is another error in "TestIntegerStackWithExceptions.java"

    There are two errors in "TestIntegerStackWithExceptions.java". Below are the classes to help you to correct.
    * A class to represent the negative size exception. (NegativeSizeException.java)
    * @author Lam Chou Yin @ Edwin
    * @version 1.0.0 18 October 2004
    public class NegativeSizeException extends Exception
          * Constructor without parameter.
         public NegativeSizeException()
              super("cannot set a negative size");
          * constructor with parameter.
          * @param message message of the exception.
         public NegativeSizeException(String message)
              super(message);
    * A class to represent the invalid stack position exception. (InvalidStackPositionException.java)
    * @author Lam Chou Yin @ Edwin
    * @version 1.0.0 18 October 2004
    public class InvalidStackPositionException extends Exception
          * Constructor without parameter.
         public InvalidStackPositionException()
              super("an invalid stack position was provided");
          * Constructor with parameter.
          * @param message message of the exception.
         public InvalidStackPositionException(String message)
              super(message);
    * A class to represent <code>IntegerStackWithExceptions</code> object. (IntegerStackWithExceptions.java)
    * @author Lam Chou Yin @ Edwin
    * @version 1.0.0 2 October 2004
    public class IntegerStackWithExceptions
          * To hold the stack of integers.
         private int[] stack;
          * To track number of items.
         private int total;
          * A constructor with one argument.
         public IntegerStackWithExceptions(int sizeIn) throws NegativeSizeException
              if (sizeIn < 0)
                   throw new NegativeSizeException();
              else
                   stack = new int[sizeIn];
                   total = 0;
          * Add an item to the array.
          * @return true when the item is successfully added.
         public boolean push(int j)
              if (isFull() == false) // checks if space in stack
                   stack[total] = j; // add item
                   total++; // increment item counter
                   return true; // to indicate success
              else
                   return false; // to indicate failure
          * Remove an item by obeying LIFO rule.
          * @return true when the item is successfully removed.
         public boolean pop()
              if (isEmpty() == false) // makes sure stack is not empty
                   total--; // reduce counter by one
                   return true; // to indicate success
              else
                   return false; // to indicate failure
          * Checks if array is empty.
          * @return true when an array is empty.
         public boolean isEmpty()
              if (total == 0)
                   return true;
              else
                   return false;
          * Checks if array is full.
          * @return true when an array is full.
         public boolean isFull()
              if (total == stack.length)
                   return true;
              else
                   return false;
          * Returns the ith item.
          * @return the ith item.
         public int getItem(int i) throws InvalidStackPositionException
              if (i < 1 || i > total)
                   throw new InvalidStackPositionException();
              else
                   return stack[i - 1]; // ith item at position i - 1
          * Return the number of items in the array.
          * @return the number of items in the array.
         public int getTotal()
              return total;
    // EasyIn.java - allows user to key in.
    import java.io.*;
    public abstract class EasyIn
      public static String getString()
         boolean ok = false;
         String s = null;
         while(!ok)
            byte[] b = new byte[512];
            try
               System.in.read(b);
               s = new String(b);
               s = s.trim();
               ok = true;
            catch(IOException e)
                System.out.println(e.getMessage());
            return s;
       public static int getInt()
          int i = 0;
          boolean ok = false;
          String s ;
          while(!ok)
             byte[] b = new byte[512];
             try
                System.in.read(b);
                s = new String(b);
                i = Integer.parseInt(s.trim());
                ok = true;
             catch(NumberFormatException e)
                System.out.println("Make sure you enter an integer");
             catch(IOException e)
                 System.out.println(e.getMessage());
         return i;
    public static byte getByte()
         byte i = 0;
         boolean ok = false;
         String s ;
         while(!ok)
            byte[] b = new byte[512];
            try
                System.in.read(b);
                s = new String(b);
                i = Byte.parseByte(s.trim());
                ok = true;
            catch(NumberFormatException e)
                System.out.println("Make sure you enter a byte");
            catch(IOException e)
                 System.out.println(e.getMessage());
         return i;
    public static short getShort()
         short i = 0;
         boolean ok = false;
         String s ;
         while(!ok)
            byte[] b = new byte[512];
            try
                System.in.read(b);
                s = new String(b);
                i = Short.parseShort(s.trim());
                ok = true;
            catch(NumberFormatException e)
                System.out.println("Make sure you enter a short integer");
            catch(IOException e)
                 System.out.println(e.getMessage());
         return i;
    public static long getLong()
        long l = 0;
        boolean ok = false;
        String s ;
        while(!ok)
           byte[] b = new byte[512];
           try
               System.in.read(b);
               s = new String(b);
               l = Long.parseLong(s.trim());
               ok = true;
           catch(NumberFormatException e)
               System.out.println("Make surre you enter a long integer");
           catch(IOException e)
                System.out.println(e.getMessage());
        return l;
    public static double getDouble()
        double d = 0;
        boolean ok = false;
        String s ;
         while(!ok)
            byte[] b = new byte[512];
            try
                 System.in.read(b);
                 s = new String(b);
                 d = Double.parseDouble(s.trim());
                 ok = true;
            catch(NumberFormatException e)
                 System.out.println("Make sure you enter a decimal number");
            catch(IOException e)
               System.out.println(e.getMessage());
        return d;
    public static float getFloat()
         float f = 0;
         boolean ok = false;
         String s;
         while(!ok)
            byte[] b = new byte[512];
            try
                System.in.read(b);
                s = new String(b);
                f = Float.parseFloat(s.trim());
                ok = true;
            catch(NumberFormatException e)
                System.out.println("Make sure you enter a decimal number");
            catch(IOException e)
                System.out.println(e.getMessage());
         return f;
      public static char getChar()
         char c = ' ';
         boolean ok = false;
         String s;
         while(!ok)
            byte[] b = new byte[512];
            try
              System.in.read(b);
              s = new String(b);
               if(s.trim().length()!=1)
                 System.out.println("Make sure you enter a single character");
               else
                    c = s.trim().charAt(0);
                    ok = true;
            catch(IOException e)
                System.out.println(e.getMessage());
         return c;
      public static void pause()
         boolean ok = false;
         while(!ok)
             byte[] b = new byte[512];
             try
                 System.in.read(b);
                 ok = true;
             catch(IOException e)
                  System.out.println(e.getMessage());
      public static void pause(String messageIn)
         boolean ok = false;
         while(!ok)
             byte[] b = new byte[512];
             try
                  System.out.print(messageIn);
                  System.in.read(b);
                  ok = true;
             catch(IOException e)
                  System.out.println(e.getMessage());
    }Finally, there are two errors in "TestIntegerStackWithExceptions.java"
    public class TestIntegerStackWithExceptions
         public static void main(String[] args)
              int size;
              IntegerStackWithExceptions stack;
              try
                   char choice;
                   // ask user to fix maximum size of stack
                   System.out.print("Maximum number of items on stack? ");
                   size = EasyIn.getInt();
                   // create new stack
                   stack = new IntegerStackWithExceptions(size);
                   // offer menu
                   do
                        System.out.println();
                        System.out.println("1. Push number onto stack");
                        System.out.println("2. Pop number from stack");
                        System.out.println("3. Check if stack is empty");
                        System.out.println("4. Check if stack is full");
                        System.out.println("5. Display numbers in stack");
                        System.out.println("6. Get any item from the stack");
                        System.out.println("7. Quit");
                        System.out.println();
                        System.out.print("Enter choice [1 - 7]: ");
                        choice = EasyIn.getChar();
                        System.out.println();
                        // process choice
                        switch(choice)
                        { // call static methods
                             case '1': option1(stack); break;
                             case '2': option2(stack); break;
                             case '3': option3(stack); break;
                             case '4': option4(stack); break;
                             case '5': option5(stack); break;
                             case '6': option6(stack); break;
                             case '7': break;
                             default: System.out.println("Invalid entry");
                   while (choice != '7');
              catch (NegativeSizeException e) // from stack constructor call
              { // source and type of error displayed
                   while (size != stack.getTotal())
                        System.out.println(e.getMessage());
                        System.out.println("due to error created by stack constructor");
                        System.out.print("Maximum number of items on stack? ");
                        size = EasyIn.getInt();
              catch (InvalidStackPositionException e) // from 'option6' method call
              { // source and type of error displayed
                   System.out.println(e.getMessage());
                   System.out.println("due to error created by call to 6th menu option");
              catch (Exception e) // just in case any other exception is thrown
                   System.out.println("This exception was not considered");
                   System.out.println(e.getMessage());
              EasyIn.pause("\nPress <Enter> to quit program");
         // static method to push item onto stack
         private static void option1(IntegerStackWithExceptions stackIn)
              System.out.print("Enter number: ");
              int num = EasyIn.getInt();
              boolean ok = stackIn.push(num); // attempt to push
              if (!ok) // check if push was unsuccessful
                   System.out.println("Push unsuccessful");
         // static method to pop item onto stack
         private static void option2(IntegerStackWithExceptions stackIn)
              boolean ok = stackIn.pop(); // attempt to pop
              if (!ok) // check if pop was unsuccessful
                   System.out.println("Pop unsuccessful");
         // static method to check if stack is empty
         private static void option3(IntegerStackWithExceptions stackIn)
              if (stackIn.isEmpty())
                   System.out.println("Stack empty");
              else
                   System.out.println("Stack not empty");
         // static method to check if stack is full
         private static void option4(IntegerStackWithExceptions stackIn)
              if (stackIn.isFull())
                   System.out.println("Stack full");
              else
                   System.out.println("Stack not full");
         // static method to display stack
         private static void option5(IntegerStackWithExceptions stackIn) throws InvalidStackPositionException
              if (stackIn.isEmpty())
                   System.out.println("Stack empty");
              else
                   System.out.println("Numbers in stack are: ");
                   System.out.println();
                   for (int i = 1; i <= stackIn.getTotal(); i++)
                        System.out.println(stackIn.getItem(i));
                   System.out.println();
         // this method throws out any InvalidStackPositionException
         private static void option6(IntegerStackWithExceptions stackIn)
              System.out.print("\nWhich position would you like to get? ");
              int position = EasyIn.getInt();
              try
                   System.out.println("This item is: " + stackIn.getItem(position));
              catch (InvalidStackPositionException ispe)
                   while (position != stackIn.getItem(position)) throws InvalidStackPositionException
                        System.out.println("Invalid position!");
                        System.out.print("\nWhich position would you like to get? ");
                        position = EasyIn.getInt();
              System.out.println();
    TestIntegerStackWithExceptions.java: Illegal start of expression at line 146
    TestIntegerStackWithExceptions.java: ';' expected at line 152Hope to reply soon.

    Next time, please don't paste all your code unless it's relevant to the problem. The compiler is telling you exactly where the problem is (most of the time, anyway), so look at the line it indicates to see if there is anything strange there or in the line above it. This type of error means you've violated the rules of Java syntax.
    In this case you are trying to add a throws clause to a while loop, which is not allowed. You can only add throws clauses to methods (and constructors).

  • There is no rt.jar in java lib could anyone help me downloading it ,or tell me where is this rt.jar, there is no rt.jar in java lib could anyone help me downloading it ,or tell me where is this rt.jar

    there is no rt.jar in java lib could anyone help me downloading it ,or tell me where is this rt.jar, there is no rt.jar in java lib could anyone help me downloading it ,or tell me where is this rt.jar

    thx for your suggestion ..but i did try to skip my code..but i am sure if u guy understand what i am trying to ask ..so i try to show my all program for u guy better undrstand my problem ...the first three paragraph of code i hope u guy could focus on it ....i try ask the user to input the cd`s title to our insert list by using a function call readString( ) and i use this method to ask the user what cd they want to be delete from the list ...but it doesn`t work when i try to perform the delete cd funtion. At first, i think it should be my deleteCd( ) problem ..but i do some testing on it..it works fine if i pass a String directly to my function instead of using readString() function to perform ...therefore, i am sure my delete function working fine....i am thinking if it is my readString() problem make my deletion does not perform well...thx for u guy help

  • Is there a web browser control in java?

    Is there a web browser control in java?

    I'm also looking to build a java-based web controller.
    I know that using Microsoft's MFC, you can build such browser control.
    The interface in C++ that they use (for web control) is IWebBrowser2
    Having a web control embedded in your application, it enables you to:
    1- start a web browser (Netscape or IE)
    2- listen to user actions on the browser (i.e. user types in a URl and hits enter. Upon doing this, a call back method will be invoked on your application , thus allowing you to write code on what exactly you want to do when you detect that a new URL was entered in the browser. For example you may send this URL through a socket connect to another user application for the purpose of sharing the web browsing activities)
    I wonder if you can achieve this in java
    Thank you very much to whom knows and can help me here on this one..

Maybe you are looking for