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.
Related
I wrote a program to read from a specific file and was wondering how would I display a custom message if that file were to not be found. What I have currently does not work, could someone explain why?
try {
//create the file writer
Fwrite = new FileWriter(file);
Fwrite.write("Student Name \t\t\t Test Score \t Grade\n");
for (int i = 0; i < size; i++) {
Fwrite.write(students[i].getStudentLName() + ", " + students[i].getStudentFName() +
" \t\t\t "+ students[i].getTestScore() + " \t\t " + students[i].getGrade() + "\n");
}
Fwrite.write("\n\nHighest Test Score: " + highestScore + "\n");
Fwrite.write("Students having the highest test score\n");
//writes the test scores in descending order
for (int i = 0; i < size; i++) {
if (students[i].getTestScore() == highestScore) {
Fwrite.write(students[i].getStudentLName() + ", ");
Fwrite.write(students[i].getStudentFName() + "\n");
}
}
//catches any errors
} catch (IOException e) {
System.err.println("File mot Found!");
e.printStackTrace();
}
//try catch method to catch any errors
System.out.println("File Complete!");
//close file
Fwrite.close();
To show file not found exception change catch block to this
catch(FileNotFoundException e){
e.printStackTrace();
}
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
CHECK THIS Link https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html
I would like to write to 2 different txt files at the same time with the same data but currently i can over-write one file but the other, help guys??
if (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y'){
credits = 10;
System.out.println("Redeemed! Congratulations! $1.00 worth of credits have been added to your account.");
int finalpoints = points - credits;
try {
FileWriter fw = new FileWriter("Transaction.history",true);
fw.write(firstname + ";" + Integer.toString(finalpoints) + ";" + "$1.00" + ";" + dateToPrintToFile + "\r\n");
fw.close();
}catch (IOException ee){
System.out.println("Input file not found!");
}
//int finalpoints1 = points - credits;
try {
FileWriter fw = new FileWriter("Points" , true);
fw.write(firstname + ";" + Integer.toString(point -credits));
fw.close();
}catch (IOException ee){
System.out.println("Input file not found!");
}
}
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.
I am trying to get my if statements to have seperate write commands such as bw.write(b + " - " + a +" = " + c + newLine); the issue is due to the newLine string and the bw
Buffer being within curley braces I cannot get those to work. any ideas?
try {
File file = new File("src/written.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
String newLine = System.getProperty("line.separator");
bw.write(b + " - " + a +" = " + c + newLine);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
JOptionPane.showMessageDialog(null,"Amount Transfered: " + b + " - " + "Previous Balance: " + a +"\nRemaning Balance: " + c);
if( c == 0){
JOptionPane.showMessageDialog(null,"Transfered granted. Balance empty","Transation successful!",JOptionPane.WARNING_MESSAGE);
}else if (c > 0){
JOptionPane.showMessageDialog(null,"Transfered granted.","Transation successful!",JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,"Transfer denied due to insufficent funds.","Transaction denied!",JOptionPane.ERROR_MESSAGE);
}
I'm not entirely sure what your goal is, but it looks like you're losing the scope on your BufferedWriter bw.
If you want to use bw outside the { } it currently resides in, declare:
BufferedWriter bw;
try {
.....
bw = new BufferedWriter(fw);
}
That way, bw is declared before the try block, which lets you use it all throughout the rest of the code as well as within the try block.
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!