Wygląd

Problemy z javą

Autor marcelinoo

15 odpowiedziarchiwum

Hardware

Wątek archiwalny, dyskusja jest zamknięta.

Mam problem z jednym MIDletem, a dokładnie z funkcją bibloteczną klasy Integer. Źródło kompiluje się bez problemu, dopiero po uruchomieniu MIDletu na java Wierless Toolkit, i przesłaniu cyfry wywala taki błąd:
java.lang.NumberFormatException: 123
at java.lang.Integer.parseInt(+214)
at java.lang.Integer.parseInt(+6)
at Server.sumuj(+4)
at Server.run(+174)

Co to może być? Chodzi dokładnie o zamiane stringu na liczbę typu int i odwrotnie:
public String sumuj(String c){
int cyfra=Integer.parseInt(c);
suma=suma+cyfra;
String pom=Integer.toString(suma);
return pom;
}
Czy ktoś ma jakieś pomysły? Proszę o rady.
Link do posta
  1. nie lepiej

    celt

    zacząć od nauki javy zamiast robienia jakiś midletów?
    Bo co ma oznaczać ten "+" przed liczbą - możesz mi wytłumaczyć?
    Uruchom sobie na poczatek ponizszy program ...
    public class Main
    {

    public Main()
    {
    }
    public static void main(String[] args)
    {
    Oblicz oblicz = new Oblicz(0);
    oblicz.sumuj("50");
    // oblicz.sumuj("+40"); <-to spowoduje wyjatekNumberFormatblablabla
    System.out.println(oblicz);
    }
    }
    class Oblicz
    {
    public Oblicz(int liczbaSt)
    {
    this.liczbaSt = liczbaSt;
    }
    public String sumuj(String c)
    {
    int cyfra=Integer.parseInt(c);
    suma = suma + cyfra;
    String pom = Integer.toString(suma);
    return pom;
    }
    public String toString()
    {
    return "suma:" + this.suma;
    }
    private int liczbaSt;
    private int suma = 0;
    }
    celt Link do posta
    1. Dzięki za wskazówki, ale niewiele mi to pomogło

      marcelinoo

      Dalej jest to samo....
      marcelinoo Link do posta
      1. to napisz

        celt

        chociaż jak wywołujesz, to będzie wiecej wiadomo
        Funkcja wygąda ok, błąd też ;) ale przyczyną wystąpienia tego błędu jest prawdopodobnie wywołanie
        Poza tym dziwi mnie wywołanie parseInt (widoczne w opisie błędu)
        Standardowo wywołanie wygląda tak: parseInt(String), a jest u ciebie parseInt(+90). Tj. 1 - nie ma "" po 2. znak + na początku
        celt Link do posta
        1. sorry, nie napisalem dokladnie oco chodzi

          marcelinoo

          w tym wywołaniu +90 to nic innego jak nr linii w pliku gdzie błąd wystąpił:)
          marcelinoo Link do posta
          1. to napisz

            celt

            jesze jak wywołujesz funkcję sumuj (tj. z jakimi parametrami)
            celt Link do posta
            1. podaje string pobrany ze strumienia

              marcelinoo

              wejściowego do zmiennej klasy StringBuffer a następnie za pomocą metody toString() konwertuje na łąńcuch. Ze strumienia pobierane są bajty i przed umieszczeniem ich w zmienej typu StringBuffer następuje rzutowanie na typ char
              marcelinoo Link do posta
  2. Chymmm

    BONUS

    a czym inicjujesz "suma"?

    Pozdrawiam
    Bonus
    BONUS Link do posta
  3. dokładnie to podam kod serwera:

    marcelinoo

    import javax.microedition.midlet.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import java.io.*;
    import java.lang.Integer;


    public class Server implements Runnable, CommandListener {
    private SocketMIDlet parent;
    private Display display;
    private Form f;
    private StringItem si;
    private int suma;
    private boolean stop;
    private Command exitCommand = new Command("Exit", Command.EXIT, 1);
    private final Alert alert = new Alert("Error", "", null, AlertType.ERROR);
    InputStream is;
    OutputStream os;
    SocketConnection sc;
    ServerSocketConnection scn;
    Sender sender;

    public class Oblicz{
    private int num;
    private int sum;

    public Oblicz(int licz){
    this.num=licz;
    this.sum=0;
    }

    public void sumuj(String c){
    int cyfra=Integer.parseInt(c);
    sum = sum + cyfra;
    }


    public String toString(){
    return "Suma: "+this.sum;
    }

    }

    public Server(SocketMIDlet m) {
    parent = m;
    suma=0;
    display = Display.getDisplay(parent);
    f = new Form("Socket Server");
    si = new StringItem("Status:", " ");
    f.append(si);
    f.addCommand(exitCommand);
    f.setCommandListener(this);
    display.setCurrent(f);
    }

    public void start() {
    Thread t = new Thread(this);
    t.start();
    }

    private String getNumber(String s)
    throws NumberFormatException {

    Oblicz ob=new Oblicz(suma);

    if (s.length() == 0) {
    alert.setString("No Argument");
    display.setCurrent(alert);
    throw new NumberFormatException();
    }

    try {
    ob.sumuj(s);
    } catch (NumberFormatException e) {
    alert.setString("argument is out of range.");
    display.setCurrent(alert);
    throw e;
    }

    return ob.toString();
    }

    public void run() {
    try {
    si.setText("Czekam na polaczenie...");
    scn = (ServerSocketConnection) Connector.open("socket://:5000");

    // Wait for a connection.
    sc = (SocketConnection) scn.acceptAndOpen();
    si.setText("Connection accepted");
    is = sc.openInputStream();
    os = sc.openOutputStream();
    sender = new Sender(os);

    // Allow sending of messages only after Sender is created

    while (true) {
    StringBuffer sb = new StringBuffer();
    int c = 0;

    while (((c = is.read()) != '\n') && (c != -1)) {
    sb.append((char) c);
    }

    if (c == -1) {
    break;
    }
    si.setText("Otrzymano cyfrę - " + sb.toString());
    sender.send(getNumber(sb.toString()));
    }
    stop();
    si.setText("Utracono polaczenie...");
    } catch (IOException ioe) {
    if (ioe.getMessage().equals("ServerSocket Open")) {
    Alert a = new Alert("Server", "Port 5000 is already taken.",
    null, AlertType.ERROR);
    a.setTimeout(Alert.FOREVER);
    a.setCommandListener(this);
    display.setCurrent(a);
    } else {
    if (!stop) {
    ioe.printStackTrace();
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public void commandAction(Command c, Displayable s) {
    if ((c == Alert.DISMISS_COMMAND) || (c == exitCommand)) {
    parent.notifyDestroyed();
    parent.destroyApp(true);
    }
    }

    /**
    * Close all open streams
    */
    public void stop() {
    try {
    stop = true;

    if (is != null) {
    is.close();
    }

    if (os != null) {
    os.close();
    }

    if (sc != null) {
    sc.close();
    }

    if (scn != null) {
    scn.close();
    }
    } catch (IOException ioe) {}
    }
    }
    marcelinoo Link do posta
    1. aha

      celt

      jeszcze jedno - trochę nie rozumiem tego co poniżej:
      while (((c = is.read()) != '\n') && (c != -1)) {
      sb.append((char) c);
      }
      Nie lepiej zastować jakiś obiekt opakowujący strumień wejściowy (o ile się mylę w interpretacji kodu ... is = sc.openInputStream(); ...)

      Czyli zastąpić tym co poniżej bez bawienia się metoda read ?

      BufferedReader we = new BufferedReader(InputStreamReader(is));
      String linia;
      while((linia = we.readLine()) ! = null)
      {
      sb.append(linia);
      }
      celt Link do posta
  4. oraz klasa Sender

    marcelinoo

    import javax.microedition.midlet.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import java.io.*;

    public class Sender extends Thread {

    private OutputStream os;
    private String message;

    public Sender(OutputStream os) {
    this.os = os;
    start();
    }

    public synchronized void send(String msg) {
    message = msg;
    notify();
    }

    public synchronized void run() {

    while (true) {

    // If no client to deal, wait until one connects
    if (message == null) {
    try {
    wait();
    } catch (InterruptedException e) {
    }
    }

    if (message == null) {
    break;
    }

    try {
    os.write(message.getBytes());
    os.write("\r\n".getBytes());
    } catch (IOException ioe) {
    ioe.printStackTrace();
    }

    // Completed client handling, return handler to pool and
    // mark for wait
    message = null;
    }
    }

    public synchronized void stop() {
    message = null;
    notify();
    }
    }
    marcelinoo Link do posta
  5. Główny MIDlet wygląda tak:

    marcelinoo

    import javax.microedition.midlet.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import java.io.*;

    public class SocketMIDlet extends MIDlet implements CommandListener {

    private static final String SERVER = "Server";
    private static final String CLIENT = "Client";

    private static final String[] names = {SERVER, CLIENT};

    private static Display display;
    private Form f;
    private ChoiceGroup cg;
    private boolean isPaused;
    private Server server;
    private Client client;


    private Command exitCommand = new Command("Exit", Command.EXIT, 1);
    private Command startCommand = new Command("Start", Command.ITEM, 1);

    public SocketMIDlet() {

    display = Display.getDisplay(this);
    f = new Form("Socket Demo");
    cg = new ChoiceGroup("Please select peer",
    Choice.EXCLUSIVE, names, null);
    f.append(cg);

    f.addCommand(exitCommand);
    f.addCommand(startCommand);
    f.setCommandListener(this);

    display.setCurrent(f);
    }

    public boolean isPaused() {
    return isPaused;
    }

    public void startApp() {
    isPaused = false;
    }


    public void pauseApp() {
    isPaused = true;
    }

    public void destroyApp(boolean unconditional) {
    if (server != null) {
    server.stop();
    }
    if (client != null) {
    client.stop();
    }
    }

    public void commandAction(Command c, Displayable s) {
    if (c == exitCommand) {
    destroyApp(true);
    notifyDestroyed();
    } else if (c == startCommand) {
    String name = cg.getString(cg.getSelectedIndex());
    if (name.equals(SERVER)) {
    server = new Server(this);
    server.start();
    } else {
    client = new Client(this);
    client.start();
    }
    }
    }

    }
    marcelinoo Link do posta
  6. Jak już podaje cały kod to jeszcze dorzuce Klienta:)

    marcelinoo

    import javax.microedition.midlet.*;
    import javax.microedition.io.*;
    import javax.microedition.lcdui.*;
    import java.io.*;


    public class Client implements Runnable, CommandListener {
    private SocketMIDlet parent;
    private Display display;
    private Form f;
    private StringItem si;
    private TextField tf;
    private boolean stop;
    private Command sendCommand = new Command("Send", Command.ITEM, 1);
    private Command exitCommand = new Command("Exit", Command.EXIT, 1);
    InputStream is;
    OutputStream os;
    SocketConnection sc;
    Sender sender;

    public Client(SocketMIDlet m) {
    parent = m;
    display = Display.getDisplay(parent);
    f = new Form("Socket Client");
    si = new StringItem("Status:", " ");
    tf = new TextField("Liczba:", "", 30, TextField.DECIMAL);
    f.append(si);
    f.append(tf);
    f.addCommand(exitCommand);
    f.addCommand(sendCommand);
    f.setCommandListener(this);
    display.setCurrent(f);
    }

    /**
    * Start the client thread
    */
    public void start() {
    Thread t = new Thread(this);
    t.start();
    }

    public void run() {
    try {
    sc = (SocketConnection) Connector.open("socket://localhost:5000");
    si.setText("Connected to server");
    is = sc.openInputStream();
    os = sc.openOutputStream();

    // Start the thread for sending messages - see Sender's main
    // comment for explanation
    sender = new Sender(os);

    // Loop forever, receiving data
    while (true) {
    StringBuffer sb = new StringBuffer();
    int c = 0;

    while (((c = is.read()) != '\n') && (c != -1)) {
    sb.append((char) c);
    }

    if (c == -1) {
    break;
    }

    // Display message to user
    si.setText("Message received - " + is.read());
    }
    //stop();
    si.setText("Connection closed");
    f.removeCommand(sendCommand);
    } catch (ConnectionNotFoundException cnfe) {
    Alert a = new Alert("Client", "Please run Server MIDlet first",
    null, AlertType.ERROR);
    a.setTimeout(Alert.FOREVER);
    a.setCommandListener(this);
    display.setCurrent(a);
    } catch (IOException ioe) {
    if (!stop) {
    ioe.printStackTrace();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public void commandAction(Command c, Displayable s) {
    if (c == sendCommand && !parent.isPaused()) {
    sender.send(tf.getString());
    }

    if ((c == Alert.DISMISS_COMMAND) || (c == exitCommand)) {
    parent.notifyDestroyed();
    parent.destroyApp(true);
    }
    }

    /**
    * Close all open streams
    */
    public void stop() {
    try {
    stop = true;

    if (sender != null) {
    sender.stop();
    }

    if (is != null) {
    is.close();
    }

    if (os != null) {
    os.close();
    }

    if (sc != null) {
    sc.close();
    }
    } catch (IOException ioe) {}
    }
    }
    marcelinoo Link do posta
  7. Chymmm

    BONUS

    parseInt

    public static int parseInt(String s,
    int radix)
    throws NumberFormatException

    Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned.

    An exception of type NumberFormatException is thrown if any of the following situations occurs:

    * The first argument is null or is a string of length zero.
    * The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
    * Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
    * The value represented by the string is not a value of type int.

    Examples:

    parseInt("0", 10) returns 0
    parseInt("473", 10) returns 473
    parseInt("-0", 10) returns 0
    parseInt("-FF", 16) returns -255
    parseInt("1100110", 2) returns 102
    parseInt("2147483647", 10) returns 2147483647
    parseInt("-2147483648", 10) returns -2147483648
    parseInt("2147483648", 10) throws a NumberFormatException
    parseInt("99", 8) throws a NumberFormatException
    parseInt("Kona", 10) throws a NumberFormatException
    parseInt("Kona", 27) returns 411787


    Parameters:
    s - the String containing the integer representation to be parsed
    radix - the radix to be used while parsing s.
    Returns:
    the integer represented by the string argument in the specified radix.
    Throws:
    NumberFormatException - if the String does not contain a parsable int.

    wyglada na brak 2 parametru
    Pozdro
    BONUS
    BONUS Link do posta
    1. lub też

      BONUS

      s nie jest parsowalne

      Pozdro
      BONUS
      BONUS Link do posta
  8. chyba już wszystko

    celt

    podałeś ;), ale nie mam możliwości aby gdzieś to wrzucić i sprawdzić co jest nie tak (m.in. dlatego że nie mam odpowiednich pakietów). Może coś później wymyśle, jak narazie sam musisz prześledzić co się dzieje po drodze (jakieś wstawki które ci wyświetlą co dzieje przez tym błędem, najlepiej jakimś debugerem)
    celt Link do posta
Zgłoś nadużycie

Kolejne wątki w dziale Hardware

Cały dział Hardware
  1. sprzedam Ryzen 2600X z płytą GB AB350M-DS3H · autor: prtc · Re: 3 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  2. Dodatkowy przenośny monitor do pracy z MB Neo. · autor: evil · Re: 5 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  3. W co obecnie zainwestować? · autor: gromki_86 · Re: 66 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  4. Gdzie odzyskać dane z dysku NVME? · autor: Kraszan · Re: 2 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  5. Szaleństwo na rynku kart graficznych · autor: rookie · Re: 9 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  6. Ładowarka do telefonu z dwoma portami USB-A · autor: gromki_86 · Re: 19 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  7. Oglądał ktoś Godzilla Minus One? · autor: gromki_86 · Re: 34 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  8. Aktywność kompa w czasie uśpienia. · autor: Dexter · Re: 9 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  9. Mały i niedrogi termometr do wnętrza, wysyłający przez wifi odczyt? · autor: gromki_86 · Re: 21 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

  10. Karta graficzna do sprzedania... · autor: malyy · Re: 5 Otwórz wątekHardware

    Wczytuję wątek…

    Otwórz wątek

Wróć na stronę główną Boarda