Boolean cannot be dereferenced

Hi all any help would be great:
Im getting these errors:
KhanAccount.java:41: boolean cannot be dereferenced
for(int i = 0; i < passwd.length(); i++)
^
KhanAccount.java:42: boolean cannot be dereferenced
if (Character.isDigit(passwd.charAt(i)))
^
KhanAccount.java:45: boolean cannot be dereferenced
if (passwd.length() >= 6 && hasDigit)
^
3 errors
This is the code:
(main method)
import java.text.*;
import javax.swing.*;
public class KhanPassword
public static void main (String [] args)
KhanAccount oneacct = new KhanAccount ();
inputacct (oneacct);
System.exit(0);
public static KhanAccount inputacct (KhanAccount aacct)
/* If an invalid password is entered (or the two entries do not match),
the user should be prompted to try again. */
/* Continuously reads a pair of passwords until the two match.*/
do { // Continuously reads the password until it is a valid one.
do {
String password = JOptionPane.showInputDialog("Enter password:\n"
+ "(must be at least six characters long and have at least one digit)");
aacct.setusername(un);
/* display a message indicating whether it is valid or not */
if (!aacct.setPassword(passwd))
JOptionPane.showMessageDialog(null, "Invalid password!");
else {
JOptionPane.showMessageDialog(null, "Valid password!");
break;
while (true);
/* The password should be prompted for twice */
String reenter = JOptionPane.showInputDialog("Re-enter password:");
/* the entries should match or a message provided to the user. */
if (!passwd.equals(reenter))
JOptionPane.showMessageDialog(null, "Two passwords don't match!");
else
JOptionPane.showMessageDialog(null, "Two passwords match!");
} while (!passwd.equals(reenter));
return aacct;
(called method)
public class KhanAccount
public String username;
public boolean password;
public String reenter;
public boolean passwd;
public static void KhanAccount (){};
     public String getusername()
     return username;
     public boolean getpassword()
     return password;
     public void setusername (String un)
     username = un;
public boolean setPassword()
password = passwd;
/* check if contains digit*/
boolean hasDigit = false;
for(int i = 0; i < passwd.length(); i++)
if (Character.isDigit(passwd.charAt(i)))
hasDigit = true;
if (passwd.length() >= 6 && hasDigit)
password = passwd;
return true;
} else
return false;
}

Btw, isn't better to initiate hasDigit to true and then when
a character is wrong set hasDigit = false and quit loop
with break or so?
And methods called set.. often returns nothing if they return
boolean they are often named with is... or so isPasswd
I've learned basic methods should be divided into three types:
constructors starts with make..
modifiers , set..
predicats , is..
//jF
/* check if contains digit*/
boolean hasDigit = false;
for(int i = 0; i < passwd.length(); i++)
if (Character.isDigit(passwd.charAt(i)))
hasDigit = true;
if (passwd.length() >= 6 && hasDigit)
password = passwd;
return true;
} else
return false;
}

Similar Messages

  • Character cannot be dereferenced?

    //output from compiler
    partA.java:72: char cannot be dereferenced
                    String theCharacterToBeAString = checkValue.toString();
                                                               ^the code
    public boolean isOperator(char checkValue)
              String theCharacterToBeAString = checkValue.toString();
              if(theCharacterToBeAString.equals("+"))
                   return true;
              else
                   return false;
         any ideas?

    Woops!
    public static boolean isOperator(char checkValue) {
        return checkValue ==  '+';

  • Error: boolean cannot be derefrenced. Help!

    Error boolean cannot be derefrenced on the toString methods for:
    public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
    if ((changeSupport != null) && (oldValue != newValue)) {
    String oValue = (oldValue.toString());
    String nValue = newValue.toString();
    changeSupport.firePropertyChange(propertyName, Boolean.valueOf(oValue), Boolean.valueOf(nValue));
    Any Ideas?

    byte, char, short, int, long, float, double and boolean are primitives.
    They don't have any members (fields or methods) that you can access by dereferencing a reference variable using the dot notation.
    If you want the String value of a boolean, there's probably a static method in Boolean, or you can use String.valueOf(bool).

  • Error boolean cannot be derefrenced?

    Error boolean cannot be derefrenced on the toString methods for:
    public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
    if ((changeSupport != null) && (oldValue != newValue)) {
    String oValue = (oldValue.toString());
    String nValue = newValue.toString();
    changeSupport.firePropertyChange(propertyName, Boolean.valueOf(oValue), Boolean.valueOf(nValue));
    If your wondering why i try to do it his way; For some strange reason the Boolean.valueOf(java.lang.boolean); method has been removed from Java.;ang.boolean in PP, so only Boolean.valueOf(java.lang.String) can be used.
    Any Ideas?

    byte, char, short, int, long, float, double and boolean are primitives.
    They don't have any members (fields or methods) that you can access by dereferencing a reference variable using the dot notation.
    If you want the String value of a boolean, there's probably a static method in Boolean, or you can use String.valueOf(bool).

  • Float cannot be dereferenced

    Hi,
    I get the following compilation error message:
    "float cannot be dereferenced"
    and i don't know what it meens.
    My code was compiling until i add the intValue methode in the last line.
    Here is the part of code :
    Dimension d,i;
    d = getSize(); // i get the size of the frame
    i = _imPanel.getSize();       // i get the size of an element in this frame
    float hp = i.height/d.height; // i calculate a ratio between those 2 size
    float wp = i.width/d.width; // for each dimansion
    _imPanel.setPreferredSize(new Dimension((getWidth()*wp).intValue(),(getHeight()*hp).intValue())); 
    // and i apply a new dimension to the element int the frame using the ration and the new size of the frame.
    As the ratio is a float and Dimension needs int in parameters, i decided to use the intValue methode to cast the float into int.
    That's it.

    Hello,
    Your problem is that you are trying to use a primitive type as if it were an object!
    You cannot call methods on the primitive types (int, float, double, etc.). Therefore, your line should be converted from:
    Dimension((getWidth()*wp).intValue(),(getHeight()*hp).ntValue()));to Dimension(new Float(getWidth()*wp).intValue(), new Float(getHeight()*hp).intValue()));Which could be done better by directly casting the values:
    Dimension((int)(getWidth()*wp), (int)(getHeight()*hp));Manuel Amago.

  • Error : char cannot be dereferenced

    I wrote this program for my test in high school. I am getting 1 error and cannot fix it. can any1 please tell me how to fix this error. The following is the program and the rror message "-
    I AM NEW HERE so i would really BENEFIT from ANY HELP !
    class testing
              static int[] search(char list[], char target) {
                   int brand[] = new int [list.length];
                   for (int i=0; i<list.length; i++) {
                        if (list[i] == target)
                        brand[i] = target.positionOf();
                   return brand;
              } // end method
              public static void main (String str[]) {
                   char list[] = {'M', 'B', 'A', 'J', 'P', 'J','M', 'J'};
                   char target = (str[0].charAt(0));
                   System.out.print ("The list = ");
                   for (int i =0; i<list.length; i++)
                        System.out.print(list[i] + ", ");
                   System.out.println();
    System.out.println ("Target letter " + target + " has been found in position " + search(list,target) + ".");
              } // end main
         } // end class     
    Error :
    C:\JPadPro\MyProjects\testing.java:14: char cannot be dereferenced
         brand[i] = target.positionOf();
    ^
    1 error
    Finished

    My program question was --> Write a program to find a symbol from a list of symbols. Your search method should return all positions in which the target symbol is found.
    According to your solution I changed to indexOf() but still i get the same error.
    class testing
              static int[] search(char list[], char target) {
                   int brand[] = new int [list.length];
                   for (int i=0; i<list.length; i++) {
                        if (list[i] == target)
                        brand[ i ] = (list[ i ].indexOf(target));
                   return brand;
              } // end method
              public static void main (String str[]) {
                   char list[] = {'M', 'B', 'A', 'J', 'P', 'J','M', 'J'};
                   char target = str[0].charAt(0);
                   System.out.print ("The list = ");
                   for (int i =0; i<list.length; i++)
                        System.out.print(list[i] + ", ");
                   System.out.println();
                   System.out.println ("Target letter " + target + " has been found in position " + search(list,target) + ".");
              } // end main
         } // end class     
    Error =
    The current directory is: C:\JPadPro\MyProjects
    C:\JPadPro\MyProjects\testing.java:14: char cannot be dereferenced
              brand[i] = (list.indexOf(target));
    ^
    1 error
    Finished

  • ERROR: int cannot be dereferenced

    hi everyone i am trying to copmile the following code
    public void refreshGUI() {
            MessageBoardQueries MBQ = new MessageBoardQueries();
            Date date = Calendar.getInstance().getTime();
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            String argDate = df.format(date).toString();
            int pNumber = MBQ.queryPending(argDate);
            int aNumber = MBQ.queryAccepted(argDate);
            int dNumber = MBQ.queryDeclined(argDate);
            pendingNumberField.setText(pNumber.toString());
            acceptedNumberField.setText(MBQ.queryAccepted(argDate));
            declinedNumberField.setText(MBQ.queryDeclined(argDate));
        }but i keep getting the error:
    int cannot be dereferenced on the line
    pendingNumberField.setText(pNumber.toString());
    does anyone know why?

    because int is a primitive datatype, hence doesn't inherit from java.lang.Object, and as such doesn't have a toString method
    try Integer.toString(pNumber) or String.valueOf(pNumber). either is equally valid

  • I get the error as 'VI's using Latched snap Boolean cannot be used'

    Dear sir/mam,
                        When I am trying to load a Boolean switch/latch until released into RT,I get the error as 'VI's using Latched snap Boolean cannot be used'.I want to know the reason why we cant downloaded these boolean into RT.what is the difference it cause in the RT.
    Thanking you
    Jayanthi.K

    Dear sir,
           I have attached the fig,In the figure 2 you can see the 6 diferents mechanical actions available for LabVIEW, however for the VIs that are going to be embedded the only 4 supported are
    the first two colums. If you use one of the two in the last colum
    n you will get the warning message when trying to download the application.
        This is my doubt.why NI Restrict these two mechanical action which is cant be downloaded into RT.It indicates the error snap/boolean latch cant be downloaded.
         I want to know the reason.........with full Technical details..........
    can u pls help me and send some more information...............with turorials...
    Thanks
    jayanthi.k
    Attachments:
    boolean.jpg ‏22 KB

  • "int cannot be dereferenced" error.. help me please

    I'm working with an array list class called PersonList and it uses attributes from a normal class called Person.
    I would like to make this method PrintPerson inside the PersonList class that should search for a specific Person given the ID as parameter to the method. the method should print all info of the Person if found, otherwise a message saying id is not valid.
    I solved it like this:
    public void PrintPerson(int id)
              System.out.println("Enter ID of the person ");
              id = Stdin.readInteger();
              //search the ID if it is in the List
              int i=0;
              while
              ((i<next)&&(!(list.getID().equals(id))))
              i++;
              //if found
              if (i<next)
                   list[i].OutputWindow();}//display the object ouput of this ID
                   else{
                   System.out.println("The following ID: " id "is not valid!");
              }//end if
         }// end of method
    my problem is with this code:
    ((i<next)&&(!(list.getID().equals(id))))
    I get this error "int cannot be dereferenced"
    what should I do? help me please
    -- Matt

    list.getID() == id                                                                                                                                                                                                                               

  • Non-static method destroyApp(boolean) cannot be referenced from a static co

    Hi guys, ive been writing, erasing and rewriting code, and finally my midlet runs well. It get complicated when i began to use the class Canvas, because the main process required values from the Canvas class. Im not sure if the program is well designed. Sugestions are apreciated.
    Well, i used static public boolean hilo; to share that variable between classes, and its working, however there is just a final procedure I want to implement, and that is that terminate the midlet when the user press the erase button.
    When I detect the button, i cant call the notifyDestroyed() method.
    Here's the code
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class TS_Online extends MIDlet implements CommandListener {
    public static Display display;                    // Objeto para que muestre en pantalla
    private SSCanvas sscInicio;               // Objeto canvas para mostrar imagenes
    private Form frmServidor;                    // Objeto forma
    private TextField ip1;                         // Direcci�n IP
    private TextField ip2;                         // Direcci�n IP
    private TextField ip3;                         // Direcci�n IP
    private TextField ip4;                         // Direcci�n IP
    private TextField puerto;                    // Puerto a conectarse
    private Command cmdEntrada;               // Objeto comando
    private Command cmdSalida;                    // Objeto comando
    private Command cmdVolver;                    // Objeto comando
    // * Constructor *
    public TS_Online() {
         display = Display.getDisplay(this);                    // Obtiene la pantalla
         sscInicio = new SSCanvas();                              // Nueva forma
         cmdEntrada = new Command("Entrada", Command.STOP, 2);
         cmdSalida = new Command("Salida", Command.STOP, 2);
         cmdVolver = new Command("Volver", Command.BACK, 1);
         sscInicio.addCommand(cmdEntrada);                    // Coloca el comando Entrada
         sscInicio.addCommand(cmdSalida);                    // Coloca el comando Salida
         sscInicio.setCommandListener(this);                    // Define la forma que escucha comandos
         ip1 = new TextField("Direcci�n IP:", "0", 3, TextField.NUMERIC);     // Caja de texto
         ip2 = new TextField(null, "0", 3, TextField.NUMERIC);
         ip3 = new TextField(null, "0", 3, TextField.NUMERIC);
         ip4 = new TextField(null, "0", 3, TextField.NUMERIC);
         puerto = new TextField("Puerto:", "24300", 5, TextField.NUMERIC);
         frmServidor = new Form("Configuraci�n");          // Titulo de la forma
         frmServidor.append(ip1);
         frmServidor.append(ip2);
         frmServidor.append(ip3);
         frmServidor.append(ip4);
         frmServidor.append(puerto);
         frmServidor.addCommand(cmdVolver);                    // Coloca el comando Salida
    // * Metodos *
    public void startApp() {
         sscInicio.hilo = true;                                   // Habilita el hilo
         new Thread(sscInicio).start();                         // Hilo en Canvas
         display.setCurrent(sscInicio);                         // Define objeto a mostrar
         sscInicio.setTitle("TicketShop S.A.");               // Titulo de la forma
    // Metodos comunes en todos los Midlet
    public void pauseApp() {
         System.out.println("*** Pausado ***");
         sscInicio.hilo = false;                                   // Detiene el hilo
    public void destroyApp(boolean unconditional) {
         sscInicio.hilo = false;
         System.out.println("*** Terminado ***");
         notifyDestroyed();
    public void commandAction(Command c, Displayable s) {
         if (c == cmdEntrada) {
              if (sscInicio.img == sscInicio.ts) {          // Configurar servidor
                   sscInicio.hilo = false;
                   sscInicio.ip = true;
                   System.out.println(sscInicio.hilo);
                   frmServidor.setCommandListener(this);
                   display.setCurrent(frmServidor);
              } else {
                   sscInicio.valido();                              // Tiquete valido
         } else if (c == cmdSalida) {
              sscInicio.invalido();                              // Tiquete invalido
         } else if (c == cmdVolver) {                         // Volver a la pantalla anterior
              sscInicio.setCommandListener(this);
              sscInicio.hilo = true;                              // Arranca el hilo
              new Thread(sscInicio).start();                    // Hilo en Canvas
              display.setCurrent(sscInicio);
              System.out.println(sscInicio.hilo);
    // * Clase graficadora *
    class SSCanvas extends Canvas implements Runnable {
    private int sleepTime;                                        // Tiempo de retrazo
    static public boolean ip;                                   // Configurar IP
    static public boolean hilo;                              // Continuar hilo
    static public Image ts = null;                         // Contenedor imagen
    static public Image rojo = null;                         // Contenedor imagenpri
    static public Image verde = null;                         // Contenedor imagen
    static public Image img = null;                         // Contenedor imagen
    static public String mensaje = null;                    // Cadena de salida
    //private CommConnection cc = null;                         // Conector para puerto
    private SocketConnection sc = null;                    // Conector para red
    private SocketConnection cc = null;                    // Conector para red
    public SSCanvas() {
         // Cargamos las im�genes a usar
         try {
              ts = Image.createImage("/TicketShop.PNG");     // Procedimiento para cargar las imagenes
              rojo = Image.createImage("/Rojo.PNG");          // Procedimiento para cargar las imagenes
              verde = Image.createImage("/Verde.PNG");     // Procedimiento para cargar las imagenes
         } catch (IOException e) {}                              // Error si no encuentra las imagenes
    void iniciar() {
         img = ts;                                                  // Imagen de bienvenida
         mensaje = "Conectando al servidor";                    // Mensaje de inicio
         // Tiempo de espera para configurar servidor
         for (sleepTime = 1;sleepTime <= 3; sleepTime++) {
              try {
                   mensaje = mensaje + ".";                    // Mensaje de inicio
                   repaint();                                        // Redibuja la pantalla
                   serviceRepaints();                              // Espera que termine
                   Thread.sleep(1000);
              } catch (InterruptedException e) {
                   System.out.println(e.toString());
         sleepTime = 50;
         img = verde;
         System.out.println("Iniciar");
    void codigo() {
    void valido() {
         img = verde;                                             // Imagen OK
         mensaje = "Tiquete OK";                                   // Tiquete valido
         AlertType.CONFIRMATION.playSound(TS_Online.display);     // Sonido
    void invalido() {
         img = rojo;                                                  // Imagen OK
         mensaje = "Tiquete Inv�lido";                         // Tiquete valido
         AlertType.ERROR.playSound(TS_Online.display);     // Sonido
    // thread que contiene el game loop
    public void run() {
         System.out.println("*** Hilo arrancado ***");
         if (img == null)
              iniciar();
         while (hilo) {
              System.out.println("Hilo");
              // Actualizar pantalla
              repaint();                                                  // Redibuja la pantalla
              serviceRepaints();                                        // Espera que termine
              try {
                   Thread.sleep(sleepTime);
              } catch (InterruptedException e) {
                   System.out.println(e.toString());
    public void keyPressed(int keyCode) {
         if (keyCode == -8) {                                        // Si presiona borrar
              hilo = false;                                   // Salir de la aplicacion
              System.out.println("*** Terminado ***");
              TS_Online.destroyApp(true);
              notifyDestroyed();
    public void paint(Graphics g) {
         // Borrar la pantalla
         g.setColor(255,255,255);
         g.fillRect (0, 0, getWidth(), getHeight());
         // Coloca la imagen correspondiente
         g.drawImage (img, getWidth()/2, 10, Graphics.HCENTER|Graphics.TOP);
         // Poner texto
         Font fuente = Font.getFont (Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
         g.setFont(fuente);
         g.setColor(0,0,0);
         g.drawString(mensaje, getWidth()/2, getHeight() - 40,Graphics.TOP|Graphics.HCENTER);
    }Im using the boolean hilo to stop the thread. I seems to work fine for me. By the way, im using 4 textFields to get the IP address, however they appear one over the other, id like to see them one next to the other, or a better way to validate an IP address.
    Thanks for the help!!

    Well, the solution was really easy, i just needed to create a reference to the midlet inside the Canvas class public SSCanvas(MIDlet m), so i got this new code, however, it seems cool in the emulator but i still cant get two comands in a row in the phone.
    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import javax.microedition.rms.*;
    public class TS_Online extends MIDlet implements CommandListener {
    public static Display display;               // Objeto para que muestre en pantalla
    private SSCanvas sscInicio = null;          // Objeto canvas para mostrar imagenes
    private Form frmServidor;                    // Objeto forma
    private StringItem subtitulo;               // Subtitulo de la forma
    private TextField[] ip;                    // Direcci�n IP
    private TextField puerto;                    // Puerto a conectarse
    private Command cmdEntrada;               // Objeto comando
    private Command cmdSalida;                    // Objeto comando
    private Command cmdVolver;                    // Objeto comando
    private String direccion;                    // Direcci�n del socket
    private RecordStore rsDireccion = null;     // Almacenamiento RMS
    // * Constructor *
    public TS_Online() {
         display = Display.getDisplay(this);                    // Obtiene la pantalla
         sscInicio = new SSCanvas(this);                    // Nueva forma con ref este midlet
         cmdEntrada = new Command("Entrada", Command.STOP, 2);
         cmdSalida = new Command("Salida", Command.STOP, 2);
         cmdVolver = new Command("Volver", Command.BACK, 1);
         sscInicio.addCommand(cmdEntrada);                    // Coloca el comando Entrada
         sscInicio.addCommand(cmdSalida);                    // Coloca el comando Salida
         sscInicio.setTitle("TicketShop S.A.");               // Titulo del canvas
         // Constructor forma Configurar Servidor
         ip = new TextField[4];                                   //
         ip[0] = new TextField(null, "190", 3, TextField.NUMERIC);     // Caja de texto
         ip[1] = new TextField(null, "65", 3, TextField.NUMERIC);
         ip[2] = new TextField(null, "161", 3, TextField.NUMERIC);
         ip[3] = new TextField(null, "158", 3, TextField.NUMERIC);
         puerto = new TextField("Puerto:", "24300", 5, TextField.NUMERIC);
         ip[0].setLayout(Item.LAYOUT_2);                         // Coloca los elementos pegados
         ip[1].setLayout(Item.LAYOUT_2);
         ip[2].setLayout(Item.LAYOUT_2);
         ip[3].setLayout(Item.LAYOUT_2);
         frmServidor = new Form("Configuraci�n");          // Titulo de la forma
         subtitulo = new StringItem("Direccion IP:", "");
         frmServidor.append(subtitulo);                         // Coloca cadena de texto
         frmServidor.append(ip[0]);
         frmServidor.append(ip[1]);
         frmServidor.append(ip[2]);
         frmServidor.append(ip[3]);
         frmServidor.append("\n ");
         frmServidor.append(puerto);
         frmServidor.addCommand(cmdVolver);                    // Coloca el comando Salida
    // * Metodos *
    public void startApp() {
         sscInicio.hilo = true;                                   // Habilita el hilo
         new Thread(sscInicio).start();                         // Hilo en Canvas
         sscInicio.setCommandListener(this);                    // Define la forma que escucha comandos
         display.setCurrent(sscInicio);                         // Define objeto a mostrar
    // Metodos comunes en todos los Midlet
    public void pauseApp() {
         System.out.println("*** Pausado ***");
         sscInicio.hilo = false;                                   // Detiene el hilo
    public void destroyApp(boolean unconditional) {
    public void salir() {
         sscInicio.hilo = false;
         System.out.println("*** Terminado ***");
         destroyApp(false);                                        // Destruir objetos
         notifyDestroyed();                                        // Salir de la aplicacion
    String cargarIP() {
    String cadena;
    // Cargar la direccion del servidor
         try {
              rsDireccion = RecordStore.openRecordStore("ipRecordStore", true );     // Crear si no existe
         } catch (Exception error) {}
         try {
              byte[] byteOutputData = rsDireccion.getRecord(1);     // Lee el primer registro
              cadena = new String(byteOutputData);
              System.out.println("Cargada: " + cadena);
         } catch (Exception error) {
              cadena = "190.65.161.158:24300";
         try {
              rsDireccion.closeRecordStore();                         // Cerrar
         } catch (Exception error) {}
         return cadena;
    void guardarIP (String cadena) {
    // Almacenar la direcci�n ip y puerto
         try {
              RecordStore.deleteRecordStore("ipRecordStore");     // Borrar si existe
         } catch (Exception error) {}
         try {
              rsDireccion = RecordStore.openRecordStore("ipRecordStore", true );     // Crear si no existe
         } catch (Exception error) {}
         try {
              byte[] byteOutputData = cadena.getBytes();     // Almacena los datos
              rsDireccion.addRecord(byteOutputData, 0, byteOutputData.length);
              System.out.println("Guardada: " + cargarIP());     // rsDireccion.getNumRecords()
         } catch (Exception error) {}
         try {
              rsDireccion.closeRecordStore();                    // Cerrar
         } catch (Exception error) {}
    void mostrarIP(String cadena) {
    int i, j=0, k;
         for (k=0; k<=2; k++) {
              i = cadena.indexOf('.', j);                         // Posicion del punto
              if (i < 0) {
                   ip[k].setString("0");                         // Si hay error coloca 0
              } else {
                   ip[k].setString(cadena.substring(j, i)); // Extrae direccion
              j = i + 1;
         i = cadena.indexOf(':', j);                              // Posicion del punto
         ip[3].setString(cadena.substring(j, i));          // Extrae direccion
         i = cadena.lastIndexOf(':');                         // Posicion dos puntos
         puerto.setString(cadena.substring(i+1));               // Extrae puerto
    public void commandAction(Command c, Displayable s) {
         if (c == cmdEntrada) {
              if (sscInicio.img == sscInicio.ts) {          // Configurar servidor
                   sscInicio.hilo = false;
                   direccion = cargarIP ();                    // Cargar del record
                   mostrarIP(direccion);                         // Mostrar en la forma
                   System.out.println("*** OK ***");
                   frmServidor.setCommandListener(this);
                   display.setCurrent(frmServidor);
              } else {
                   sscInicio.entrada = true;                    // Tiquete entrada
                   AlertType.ERROR.playSound(TS_Online.display);     // Sonido
         } else if (c == cmdSalida) {
              sscInicio.entrada = false;                         // Tiquete salida
              AlertType.ERROR.playSound(TS_Online.display);     // Sonido
         } else if (c == cmdVolver) {                         // Volver a la pantalla anterior
              direccion = ip[0].getString() + "." + ip[1].getString() + "."
                   + ip[2].getString() + "." + ip[3].getString() + ":" + puerto.getString();
              guardarIP(direccion);                              //Almacenar en record
              sscInicio.setCommandListener(this);
              sscInicio.hilo = true;                              // Arranca el hilo
              new Thread(sscInicio).start();                    // Hilo en Canvas
              display.setCurrent(sscInicio);
              System.out.println(sscInicio.hilo);
    // * Clase graficadora *
    class SSCanvas extends Canvas implements Runnable {
    private int sleepTime;                                        // Tiempo de retrazo
    static public boolean entrada = true;                    // Tiquete de entrada
    static public boolean hilo;                              // Continuar hilo
    static public Image ts = null;                         // Contenedor imagen
    static public Image rojo = null;                         // Contenedor imagenpri
    static public Image verde = null;                         // Contenedor imagen
    static public Image img = null;                         // Contenedor imagen
    static public String mensaje = null;                    // Cadena de salida
    static public String mensaje2 = "";                    // Cadena de salida Codigo de barras
    MIDlet midlet;                                                  // Enlace al midlet inicial
    CommConnection cc = null;                         // Conector para puerto
    //SocketConnection sc = null;                    // Conector para red
    //SocketConnection cc = null;                    // Conector para red
    public SSCanvas(MIDlet m) {
         midlet = m;                                                  // Referencia al MIDlet iniciado
         // Cargamos las im�genes a usar
         try {
              ts = Image.createImage("/TicketShop.PNG");     // Procedimiento para cargar las imagenes
              rojo = Image.createImage("/Rojo.PNG");          // Procedimiento para cargar las imagenes
              verde = Image.createImage("/Verde.PNG");     // Procedimiento para cargar las imagenes
         } catch (IOException e) {}                              // Error si no encuentra las imagenes
         img = ts;                                                  // Imagen de bienvenida
         mensaje = "Conectando";
         mensaje2 = "";                                             // Mensaje de inicio
    void iniciar() {
         img = ts;                                                  // Imagen de bienvenida
         // Tiempo de espera para configurar servidor
         for (sleepTime = 1;sleepTime <= 3; sleepTime++) {
              try {
                   mensaje = mensaje + ".";                    // Mensaje de inicio
                   repaint();                                        // Redibuja la pantalla
                   serviceRepaints();                              // Espera que termine
                   Thread.sleep(1000);
              } catch (InterruptedException e) {
                   System.out.println(e.toString());
         mensaje = "Conectado!";
         img = verde;
         repaint();                                        // Redibuja la pantalla
         serviceRepaints();                              // Espera que termine
         sleepTime = 50;
         System.out.println("Iniciar");
    void codigo() {
         try {
              System.out.println("Leyendo");
              CommConnection cc = (CommConnection)Connector.open("comm:com0;baudrate=9600");
              //cc = (SocketConnection)Connector.open("socket://127.0.0.1:24300");
              //int baudrate = cc.getBaudRate();
              InputStream ic  = cc.openInputStream();          // Entrada serial
              //OutputStream oc = cc.openOutputStream();
              StringBuffer sbCodigo = new StringBuffer();     // Cadena de diferentes tipos de datos
              int ch = 255;
              while(ch > 32) {
                   ch = ic.read();
                   //oc.write(ch);
                   if (ch > 32)
                        sbCodigo.append((char)ch);
              mensaje2 = sbCodigo.toString();                    // Codigo de barras
              if (mensaje2.equals("2864634059CULIB")) {
                   valido();
              } else {
                   invalido();
              ic.close();                                             // Cierra las conexiones
              //oc.close();
              cc.close();
         } catch (Exception e) {
              Alert a = new Alert("Error!", e.toString(), rojo, AlertType.ERROR);
              a.setTimeout(Alert.FOREVER);                                   // Alerta hasta que oprima boton
              TS_Online.display.setCurrent(a);               // Despues de la alerta vuelve a Inicio
              try {
                   Thread.sleep(5000);
              } catch (Exception x) {}
    void valido() {
         img = verde;                                             // Imagen OK
         mensaje = "Tiquete OK";                                   // Tiquete valido
         AlertType.CONFIRMATION.playSound(TS_Online.display);     // Sonido
    void invalido() {
         img = rojo;                                                  // Imagen OK
         mensaje = "Tiquete Inv�lido";                         // Tiquete valido
         AlertType.ERROR.playSound(TS_Online.display);     // Sonido
    // thread que contiene el game loop
    public void run() {
         System.out.println("*** Hilo arrancado ***");
         if (img == ts)
              iniciar();
         while (hilo) {
              //System.out.println("Hilo");
              // Leer codigo de barras
              codigo();
              // validar codigo de barras
              //validar();
              // Actualizar pantalla
              repaint();                                                  // Redibuja la pantalla
              serviceRepaints();                                        // Espera que termine
              try {
                   Thread.sleep(sleepTime);
              } catch (InterruptedException e) {
                   System.out.println(e.toString());
    protected void keyPressed(int keyCode) {
    mensaje = Integer.toString(keyCode);
    //int action = getGameAction(keyCode);
         if ((keyCode == -8) || (keyCode == 42)) {               // Si presiona borrar o *
              AlertType.ERROR.playSound(TS_Online.display);     // Sonido
              ((TS_Online)midlet).salir();
         } else if (keyCode == -51 || keyCode == -52 || keyCode == -53) {
              AlertType.ERROR.playSound(TS_Online.display);     // Sonido
    public void paint(Graphics g) {
         // Borrar la pantalla
         g.setColor(255,255,255);
         g.fillRect (0, 0, getWidth(), getHeight());
         // Coloca la imagen correspondiente
         g.drawImage (img, getWidth()/2, 20, Graphics.HCENTER|Graphics.TOP);
         // Poner texto
         Font fuente = Font.getFont (Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
         g.setFont(fuente);
         g.setColor(0,0,0);
         g.drawString(mensaje, getWidth()/2, getHeight()/2,Graphics.TOP|Graphics.HCENTER);
         g.drawString(mensaje2, getWidth()/2, 5,Graphics.TOP|Graphics.HCENTER);
    }

  • Why am I getting 'VIs using Latched/Snap boolean cannot be downloaded' message when trying to download to the FP2000?

    Using LabVIEW 6.0.3 RT

    LabVIEW RT has two modes of opeation: Development mode and Deployed mode.
    In the development mode Labview provides you with a USER INTERFACE for debugging purposes but at the end you want to be in the Deployed mode where you develop the user interface to communicate with your embedded vi with differents ways like TCP/IP, UDP, DataSocket, VI SERVER, etc.
    Therefore, not all the mechanical actions for boolean controls/indicators are supported under real time.
    Remember that you dont have a physical interaction with the interface.
    In the figure 2 you can see the 6 diferents mechanical actions available for LabVIEW, however for the VIs that are going to be embedded the only 4 supported are
    the first two colums. If you use one of the two in the last colum
    n you will get the warning message when trying to download the application.
    You will need to use the supported mechanical actions for your application.
    Attachments:
    figure2.bmp ‏2144 KB

  • This program show me "int cannot be dereferenced" as error can you help me?

    public class Factorial{
         public static void main (String [] args){
              if (args.length<1){
                   showmsg("a Integer Please");
                   else if (args.length>1){
                        showmsg ("Only a Integer please");
                        else {
                             int n;
                             try {
                                  n= Integer.parseInt(args[0]);
                             catch (NumberFormatException nfe){
                             showmsg ("a Integer not a String please"); //call to chow message method
                        factorial(n);
         //show a message
         private static void showmsg (String texto){
              System.out.println(texto);
         //factorial procedure
         public static void factorial (int n){
              int fac=1;
              for (int i=1;i<=n;i++){
                   fac*=i;
              String resu = fac.toString();
              showmsg(resu);
    }

    Thanks for your help, I did change other lines too... (if some body wish Run)
    try {
            int n;
            n= Integer.parseInt(args[0]);
            factorial(n);
    catch (NumberFormatException nfe){
                //call to show message method
               showmsg ("a Integer not a String please");
               showmsg (nfe.getMessage());
    }

  • 6 errors trying to compile TalkClientApplet.java

    Hello:
    Trying to compile TalkClientApplet.java at:
    http://java.sun.com/docs/books/tutorial/deployment/applet/ex5/TalkClientApplet.java
    on the jdk1.5.0_06, Windows XP, and I received the following errors:
    TalkClientApplet.java:94:incomparable types:boolean and <nulltype>
    if(receivedThread ==null){
    TalkClientApplet.java:99:incompatible types
    found:java.lang.Thread
    required:boolean
    receiveThread=new Thread(this);
    TalkClientApplet.java:100:boolean cannot be dereferenced
    receiveThread.start();
    TalkClientApplet.java:150:incompatible types
    found :<nulltype>
    required:boolean
    receiveThread=null;
    TalkClientApplet.java:186:incomparable types:boolean and <nulltype>
    if(receiveThread==null){
    TalkClientApplet.java:258:incomparable types:java.lang.Thread and
    boolean while (Thread.currentThread()==receiveThread){
    Thanks in advance for your help.

    Hello:
    I am following the code from:
    http://java.sun.com/docs/books/tutorial/deployment/applet/ex5/TalkClientApplet.java
    which was pointed to from:
    http://java.sun.com/docs/books/tutorial/deployment/applet/workaround.html
    This is the section:
    private void start(boolean onEDT) {       
    if (DEBUG) {
    System.out.println("In start() method.");
    if (receiveThread == null) {
    trysted = false;
    os = null;
    is = null;
    socket = null;
    receiveThread = new Thread(this);
    receiveThread.start();
    if (DEBUG) {
    System.out.println(" Just set everything to null and started thread.");
    enableGUI(onEDT);
    Thanks

  • Removing a value from an array

    I have searched the forums, and found many post about this, but with different variances.
    i have an array, where if a user passes an argument that already exists in the array, it will remove that value from the array. when i run the code below i get a boolean exception. i "think" my thinking is correct, but i cannot seem to put it into code terms (HAH! thats a first eh?).
    what exactly be the difference to setting the position to 0 or to null?
    public void remove(int lessNum) throws NotFoundException {
       for( int i=0;i<this.occupied.length;i++) {
            if(occupied.equals(lessNum)
         occupied[i] = null;
         else
         throw new NotFoundException();
    }//end for
    }//end remove
    this is the exception i get: boolean cannot be dereferenced
                        if(occupied[i].equals(lessNum)
    ^
    Thanks,
    J

    Hi.
    (You have a few typos in your code, but I'm assuming that's because you typed it in again when you sent your posting rather than copying and pasting it. Your compilation error is also not consistent with the code, but I'll take a guess at what is going on)
    There are a number of things that are strange about the code example.
    1. It looks like your 'occupied' field is a boolean[] (the compilation error indicates that this is the case). That means each element of occupied is a primitive boolean, not a reference. Therefore trying to dereference it makes no sense. This is what the compiler error is telling you. Note that this is not an exception.
    2. Now looking at the intent of what I think you're trying to do... I think you are trying to determine if element i of the 'occupied' array is equal to the parameter 'lessNum'. This is nonsensical since the elements of 'occupied' are booleans and lessNum is an int.
    3. Finally, trying to set an element of 'occupied' to null, doesn't make sense because the elements of 'occupied' are not references, but primitives.
    Regarding your question about the difference between setting something to 0 or null: I assume you come from a C or C++ background where 0 and null are the same thing. In Java, null is not equivalent to 0 but is instead a special value for a variable of reference type that means that the variable is not currently referring to anything. In C and C++ if a pointer has the value 'null' or 'zero' it simply means that any attempt to dereference it will mean an attempt to look for an object at memory address 0 which will usually result in unimaginable horrors (alright, it's not that bad).
    Regards,
    Lance
    Lance Walton - [email protected]
    Team In A Box - Software without Tragedy
    http://www.teaminabox.co.uk

  • HELP!!!.. prob with boolean

    hi there... im a reaaal newbie at this stuff, so pls go easy on me and help me out ;)
    im trying to compare 2 sets (x,y) & (a,b) of numbers using boolean expressions... i tried doing this:
    if (a.isEqual(x) && b.isEqual(y))
    System.out.println("\nBoth equal");
    else
    System.out.println("\nNumbers are not equal");
    but it didnt work... the error msg is:
    ComplexType.java:60: double cannot be dereferenced
    if (a.isEqual(x) && b.isEqual(y))
    ^
    ComplexType.java:60: double cannot be dereferenced
    if (a.isEqual(x) && b.isEqual(y))
    ^
    2 errors
    please help me out with this... the text that i got doesnt say much about boolean expressions, so im really stuck!!

    You can't do it the other way because numbers like 42 or 3.14159 are not objects in Java, they are primitives.
    Primitives are just plain data; they don't have a class or or any members (like methods you could call). Had you been using objects "a.equals(x)" would have been just fine (and prefferable to "a == x").
    It gets a little more complicated when there are also wrapper classes for primitives in Java; that is, you can have objects that represent simple numbers or characters.
    Here's a simple example that might help: // the class Double is a wrapper for the type double
    Double n1 = new Double(1);
    Double n2 = new Double(1);
    double n3 = 1;
    double n4 = 1;
    // see if n1 and n2 are equal
    System.out.println(n1.equals(n2));
    // see if n1 and n2 are the same object
    System.out.println(n1 == n2);
    // see if n3 and n4 are equal
    System.out.println(n3 == n4);
    // try some simple arithmetic:
    // System.out.println(n1 + n2); Doesn't work since n1 and n2 refer to objects
    System.out.println(n3 + n4);

Maybe you are looking for