NoSuchElementException when setting a timeout on the socket - java

I wanted to set a timeout when a client read. the routine supposed to throw an InterruptedIOException but instead it throws NoSuchElementException on System.out.println("echo: " + _in.nextLine()); what am I doing wrong ?
this is my methode
public void startUserInput()
{
try {
_out = new PrintWriter(_echoSocket.getOutputStream(), true);
_in = new Scanner(new InputStreamReader(_echoSocket.getInputStream()));
Scanner stdIn = new Scanner(new InputStreamReader(System.in));
System.out.print("Input: ");
while (stdIn.hasNextLine()) {
_out.println(stdIn.nextLine());
System.out.println("echo: " + _in.nextLine());
System.out.print("Input: ");
}
stdIn.close();
}catch (InterruptedIOException exception){
System.err.println("The server is not responding " + _serverHostname);
}
catch (IOException e) {
System.out.println("error" + e.getLocalizedMessage());
}}
and this is my connection
public boolean establishConnection()
{
System.out.println ("Connecting to the host " +
this.getServerHostname() + " au port " + this.getServerPort());
try {
_echoSocket = new Socket();
_echoSocket = new Socket(this.getServerHostname(), this.getServerPort());
_echoSocket.setSoTimeout(10000);
System.out.println(_echoSocket.getOutputStream());
return _echoSocket.isConnected();
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + this.getServerHostname());
return false;
} catch (IOException e) {
System.err.println("Error while connecting to the server : " +
this.getServerHostname() + ":" + this.getServerPort());
return false;
}
}
Thanks

The reason is that when you invoked _in.nextLine() there is no line to be read in from the from the Scanner object _in.
What you did in the while loop was to check for stdIn.hasNextLine() but you did not check if _in has a nextLine() that can be read.
For details on the exception, you can check out:
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html#nextLine()
hope it helps :) Cheers!

Related

how to stop a process when "ctrl+c" is pressed in java?

i am using the following in one of my application.
public static void concatenation(List<String> commands) throws IOException {
if (commands.get(1).equals(">")) {
String path = history.getFilePath();
File file = new File(path + "\\" + commands.get(2));
if (file.exists() && file.isFile()) {
try (FileWriter writer = new FileWriter(file)) {
Scanner scanner = new Scanner(System.in);
String line;
System.out.println("Write to file. Press Ctrl+C to stop.");
while (true) {
try {
line = scanner.nextLine();
writer.write(line + System.lineSeparator());
writer.flush();
} catch (Exception e) {
System.out.println("Interrupted. Stopping...");
break;
}
}
scanner.close();
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
} else {
System.out.println("bash : " + commands.get(1) + " : unrecognized operator");
}
}
i want to exit out of the while loop when ctrl + c is pressed. And it is a console application. How to achieve this?

Java.lang.String cannot be converted to int

In my program that turns roman numerals into arabic numbers I have run across the error
incompatible types: java.lang.String cannot be converted into int
Here is my code
if ( Character.isDigit(TextIO.peek()) ) {
int arabic = TextIO.getlnInt();
try {
RomanNumerals N = new RomanNumerals(arabic);
TextIO.putln(N.toInt() + " = " + N.toString());
}
catch (NumberFormatException e) {
System.out.println("Invalid input.");
System.out.println(e.getMessage());
}
}
else {
String roman = TextIO.getln();
try {
RomanNumerals N = new RomanNumerals(roman);
System.out.println(N.toString() + " = " + N.toInt());
}
catch (NumberFormatException e) {
System.out.println("Invalid input.");
System.out.println(e.getMessage());
}
}
I am using BlueJ and the error is being highlighted over "(roman)"
Guesswork here... but probably your class RomanNumerals does not have a constructor taking a string as an argument like
public RomanNumerals(String r) {
Thats why calling it that way:
RomanNumerals N = new RomanNumerals(roman);
Is not permitted.
I'm looking at TextIO.putln(N.toInt() + " = " + N.toString()); and imagining that N.toInt() returns an int and the compiler is confused when you try adding " = " to it.
Try TextIO.putln(Integer(N.toInt()).toString() + " = " + N.toString());.

Why are the last two instructions unreachable code?

Eclipse spots them as unreachable code, which apparently is a code that will never be read for there's no path to reach it, but I don't see why. The instructions are inside a main() method
//leemos
FileInputStream fis;
ObjectInputStream ois;
Alumno alumnoLeido = null;
String cadena ="";
JTextArea area = new JTextArea(6,1);
while(true){
try {
fis = new FileInputStream("alumnos.txt");
ois = new ObjectInputStream(fis);
alumnoLeido = (Alumno) ois.readObject();
ois.close();
cadena = "Alumno " + alumnoLeido.getNombre() + " " + alumnoLeido.getApellido() + " vive en "
+ alumnoLeido.getDireccion() + " y tiene una beca de " + alumnoLeido.getBeca() + " euros \r\n";
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
area.append(cadena);
JOptionPane.showMessageDialog(null, area, "Alumnos",1);
while(true) is an infinite loop. Without a break, the loop will never terminate and allow the following code to execute. So, you will never reach the remaining statements.
They are unreachable because your while loop will never terminate.

How to control Windows from Android Keyboard?

I created the mobile app on client side for Android successfully.
Then Server side, that is windows server code also created. I can able to type all the letters numbers and all.
My problem is using shift key and "#" key. I need "#" into my project. When I press the "#" crashes the connection and says...
Invalid key code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at pcHotkey.keyboardServer$Capitalizer.run
Now, how should I type "#" with my app. Then I press shift key it was passing correctly and it was not stopping the pressed state.
My code goes here,
1st class:
aMap.put("Shift", KeyEvent.VK_SHIFT);
aMap.put("At", KeyEvent.VK_AT);
try{
robo = new Robot();
}
catch(Exception e)
{}
ServerSocket listener = new ServerSocket(9898);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
2nd class :
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Send a welcome message to the client.
out.println("Hello, you are client #" + clientNumber + ".");
out.println("Enter a line with only a period to quit\n");
while (true) {
String input = in.readLine();
System.out.println(input);
if(input.equals("Caps")){
Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
;
}
else if(input.equals("At"))
{
log("Log Value : "+ input);
//Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_SHIFT, true);
robo.keyPress(aMap.get("At"));
//Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_SHIFT, true);
}
else
robo.keyPress(aMap.get(input));
}
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}
I did by passing the keycode of "SHIFT" and "2". Problem got fixed now.

Reading And Writing to text file

I've written this code to read in a file and then ask for a mark, for each name in the file. And if the mark is over 40 its a pass and below is a fail and writes each name to the corresponding file. But I get an error at line 27 which: while(namesFile.hasNext() here's my code:
import java.io.*;
import java.util.*;
public class TestResults {
public static void main(String[] args) {
String errs = "";
Scanner k = new Scanner(System.in);
try {
try (
Scanner namesFile = new Scanner(new File("Names.txt"));
PrintWriter passFile = new PrintWriter("Pass.txt");
PrintWriter failFile = new PrintWriter("Fail.txt");) {
while (namesFile.hasNext()) {
try {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
}
} // Checks to see if file is there.
catch (IOException ioe) {
System.out.println("ERROR: " + ioe.getMessage());
}
}
}
public class TestResults {
public static void main(String[] args) {
Scanner namesFile;
PrintWriter passFile;
PrintWriter failFile;
String errs = "";
Scanner k = new Scanner(System.in);
try {
try {
namesFile = new Scanner(new File("D:/Names.txt"));
passFile = new PrintWriter("D:/Pass.txt");
failFile = new PrintWriter("D:/Fail.txt");
try {
while (namesFile.hasNext()) {
String tempLine = namesFile.nextLine();
System.out.println("Please Enter Mark For " + tempLine + " : ");
int mark = k.nextInt();
if (mark >= 40) {
passFile.println(tempLine + " " + mark + "%");
} else {
failFile.println(tempLine + " " + mark);
}
}
} catch (InputMismatchException ime) {
String valueStr = namesFile.next();
errs += "\n\t" + valueStr;
} finally {
namesFile.close();
passFile.close();
failFile.close();
}
}
catch(IOException ioe){
System.out.println("ERROR: " + ioe.getMessage());
}
} // Checks to see if file is there.
catch (Exception e) {
}
}
}

Categories

Resources