Issue with the Scanner input - java

I am writing a code to get data from a radiometer sensor connected to one of the "COMs" of the computer, to get the measurement i have to communicate with that sensor throw "COM7" and write the command "gi" to get a value like ""9.919e-08" for example from the command user interface.
Now i have a problem with the code and it is giving me that error "No line found"
and here is the code
package reading_data;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import com.fazecast.jSerialComm.SerialPort;
public class main {
public static void main(String[] args) throws IOException, InterruptedException {
SerialPort sp= SerialPort.getCommPort("COM7");
sp.setComPortParameters(115200, 8, 1, 0);
sp.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0);
sp.openPort();
if(sp.isOpen()) {
System.out.println("Port is open");
PrintWriter output=new PrintWriter(sp.getOutputStream());
Scanner data=new Scanner(sp.getInputStream());
output.println("gi");
String ssss=data.nextLine();
System.out.println("--++++---->"+ssss);
}else {
System.out.println("Port is not open");
}
sp.closePort();
}
}
and here is the error i get
Port is open
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at reading_data.main.main(main.java:26)
May you please tell me where is my mistake?
thanks in advance

Try like this:
output.flush();
if(data.hasNextLine()) {
String ssss=data.nextLine();
}
If no next line, then don't call the nextLine.
Edit.: flush needs to be done.

Related

Trying to run a server with multiple clients where the client will tell me the date but my java.util.Date is not importing correctly

Hi I am currently doing a project where I have multiple clients telling the server a date however my java.util.date is not working and running me back an error message.
How would I fix this issue code is provided below as well as the message. I must also add I am writing said project in java and using the eclipse IDE.
package clientServer;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public static void main(String[] args) throws IOException {
try (ServerSocket listener = new ServerSocket(7000)) {
System.out.println("The date server is running...");
while (true) {
try (Socket socket = listener.accept()) {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
}
}
}
}
}
the 2 errors
for import java.util.Date it says import java.util.Date cannot be resolved
and for the code out.println(new Date()) it says Date cannot be resolved into a type
I have tried cleaning the project and using alt 5 to give it a direct path however this has not worked

Jama Matrix printwriter error

I am using JAMA matrix in my project. I need to write down a Jama matrix in text file. For that I write down this code.
package Xdata;
import Jama.Matrix;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class File_r {
public static void main(String args[]) {
Matrix A = new Matrix(10, 10);
try {
PrintWriter write1 = new PrintWriter(new File("/home/robotics//IdeaProjects/Data_arrange/src/Xdata/mu_X.txt"));
A.print(PrintWriter write1,9,6);// error in this line
}
catch(FileNotFoundException ex) {
System.out.println(ex);
}
}
}
But it throws errors:
/home/robotics/IdeaProjects/Data_arrange/src/Xdata/File_r.java
Error:(13, 32) java: ')' expected
Error:(13, 33) java: not a statement
Error:(13, 39) java: ';' expected
I wtite down this code in intellj idea. Can any one tell me why I get this error?
I did check the Jama api for Matrix.java. it looks you are trying to use the print method with three parameter in the below snippet . please re-write it correctly.
fix it as below
A.print(write1,9,6);// error in this line
I solved this problem. I think it is helpful for those who are new to Jama Matrix and face a problem like that. Here is my Solution:
package Xdata;
import Jama.Matrix;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class File_r {
public static void main(String args[]) {
Matrix A = new Matrix(10, 10);
PrintWriter writer=null;
try {
writer = new PrintWriter("/home/robotics//IdeaProjects/Data_arrange/src/Xdata/mu_X.txt");// So basically I change this line
A.print(writer,2,2);
writer.close();// Add this line
}
catch(FileNotFoundException ex) {
System.out.println(ex);
}
}
}
This solve my problem. As there is very less documentation of JAMA Matrix I think this is really help ful for reader.

Bind error even with setReuseAddress(true) [duplicate]

This question already has an answer here:
Address reuse not working on new Java Runtime Environment
(1 answer)
Closed 5 years ago.
Maybe I misunderstand the use of this code, but from what I understand, calling setReuseAddress(true) will allow the port to be used even if the computer still thinks it is in use.
Scenario: I have the below code. When it crashes it does not close the port, so it throws a bind error on next launch. I have used setReuseAddress(true) to try to force it to open the port, but it throws the same error. If this is the right code, how do I use it? If it's the wrong code, what will allow this behavior?
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class ServerPsswd {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket();
listener.setReuseAddress(true);
listener.bind(new InetSocketAddress(9090));
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println("tada!");
out.println("yays");
} finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
}
https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#setReuseAddress(boolean)
It is to allow connections during the timeout period AFTER the current connection has been closed

Data corrupting on program close in jxl

Im using jxl to store data entered in by the user into an excel spreadsheet. I want to be able to close my program while its running and open up the excel spreadsheet and view the data. Whenever I do this, I get a message that says that it is in a different format than specified in the file extension. Here is my code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import jxl.*;
import jxl.write.*;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class ReadWriteTest
{
public static void main(String[] args) throws BiffException, IOException, RowsExceededException, WriteException
{
Scanner scan = new Scanner(System.in);
int i = 1;
Integer iAlliance = -1;
File test = new File("C:\\test.xls");
WritableWorkbook wb = Workbook.createWorkbook(test);
while(iAlliance != 0 && i != 5)
{
WritableSheet sheet = wb.createSheet("Sheet" + i, i);
iAlliance = scan.nextInt();
WriteExcel.addNumber(sheet, 0, 0, iAlliance);
iAlliance = scan.nextInt();
WriteExcel.addNumber(sheet, 1, 0, iAlliance);
i++;
}
wb.write();
wb.close();
}
}
"close my program while its running"
Your code needs to handle that. Right now, it just gets killed at any point (probably in that loop), and nothing after that point happens. The WriteableWorkbook never gets write() or close() called, and the file is probably corrupted.
So see this, try adding some simple output at various places, like "got to line number XXX". Run it, close it, and see how far it got.
You'll probably need to wrap the bulk of your code in a try-catch-finally. The loop is inside the try, the catch handles the lightning-out-of-the-blue program closing from that pesky human at the keyboard, and the finally closes up the workbook file properly.

NullPointerException in BufferedReader

I'm trying to use BufferedReader to import strings from a .txt file into an Arraylist, then using a random method to randomly pick a string inside the Arraylist.
But whenever I run this code, it gives me a java.lang.NullPointerException.
What should I do to fix this problem? Thank you in advance.
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
the .txt file in question consists of a few lines of words.
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Random;
public class WordList{
private static ArrayList<String> words =new ArrayList<String>();
public void main(String[] args) throws IOException {
ArrayListCon("Majors.txt");
System.out.println(words);
}
private void ArrayListCon(String filename) throws IOException{
String line;
BufferedReader br = null;
br = new BufferedReader(new FileReader(filename));
while (( line = br.readLine()) != null){
words.add(line);
}
br.close();
}
public static String getRandomWord(){
Random r = new Random();
String randomWord = words.get(r.nextInt(words.size()));
return randomWord;
}
}
After making the following changes, your code worked perfectly for me, and i never saw the null pointer exception error.
1 ) I first made the method main static, as I was getting an error that there was no main method found:
public static void main(String[] args) throws IOException {
2 ) I also made the ArrayListCon method static
private static void ArrayListCon(String filename) throws IOException{
3 ) I made a file called Majors.txt with the contents:
hello
hi
there
my
words
are
cool
4 ) Finally, I just compiled and ran the program, with the following output:
javac WordList.java
java WordList
[hello, hi, there, my, words, are, cool]
I believe the issue is coming up with how you are running the code (edu.rice.cs.drjava.model.compiler.JavacCompiler)
The exception is arising as a result of a bug in both your code and in the DrJava code.
In your code, you need to make your main method static.
In the DrJava code, they need to add a check for Modifier.isStatic(m.getModifiers()) in the JavacCompiler.runCommand method.

Categories