Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Cant understand why...  RSS feed

 
Jessid Leon Velez Gutierrez
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello. I am sorry for asking this thing, but I cant understand why this code works the way it does. This is a segment of a program to read the serial port that I extracted from http://rxtx.qbang.org/wiki/index.php/Examples. My question is about this while...cant understand how it works.

Thanks a lot!

public static class SerialReader implements Runnable {
InputStream in;

public Lector( InputStream in ) {
this.in = in;
}

public void run() {
byte[] buffer = new byte[1024];
int len = -1;
try {
while ( ( len = this.in.read(buffer)) > -1 ) {
System.out.print(new String(buffer,0,len));
//System.out.println("La longitud del buffer es: " + len);
}
System.out.println("alguna cosa");
} catch ( IOException e ) {
e.printStackTrace();
}
}
}
 
Joe Ess
Bartender
Posts: 9421
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jessid Leon Velez Gutierrez:
I cant understand why this code works the way it does.


Maybe you could clue us in to what the code does. This code will not execute as a stand-alone program so we can't see for ourselves.
What do you expect the code to do and why does it not meet your expectations?
 
Jessid Leon Velez Gutierrez
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. Thanks for the interest. What the program does is just read a serial port,and prints the characters you send to the PC in the command line. I was expecting that the while statement run only once and exited when len = -1, due to the lack of chars in the buffer, and when I sent new data, it didnt print it in the command line, but it never goes out the while...and that is what I cant understand well: why is that a never ending while. i think i havent understood well all this stuff of streams....i better begin to study again, jijiji

Thanks again!

English is not my native language. I hope I have not made a lot of mistakes, or at least the idea was transmitted
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15985
86
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the InputStream? Is it a special kind of InputStream that reads data from a serial port?

Maybe the input stream never returns -1; maybe, if no data available, it just blocks until data is available. Look it up in the documentation of the serial port communications package that you're using.
 
Willie Smits can speak 40 languages. This tiny ad can speak only one:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!