java client-server program crashes after first iteration through loop - java

I am having a problem with a client-server application. The program runs correctly through until the second time the client must input data. Upon debugging the code it appears that the client always crashes on the line linesIn = din.readInt(); on the second iteration through the loop.
as suggested I added a try catch block around the integer parsing and it seems to have helped move the program further along but now when run the program will only give the correct output to the user once and after that will display the list of options available twice and then not accept any further input
The following output is displayed in the client:
The address and hostname are: BOO-PC/192.168.0.8
The Hostname: BOO-PC
The Address only: 192.168.0.8
Server: Welcome please make your selection from the options below
Server: 1: make a booking
Server: 2: cancel a booking
Server: 3: view available films
Server: 4: logout
Client:
3
Server: Title :Film1
Server: Time : 10.3
Server: Date : 10 7 2013
Server: Price : 5.0
Server: Referance Number : 55
Server:
Client:
Server:
and this error on the server
Exception in thread "serverThread" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at systemssoftwarebookingsystem.serverThread.run(serverThread.java:45)
server thread code:
package systemssoftwarebookingsystem;
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class serverThread extends Thread
{
private Socket socket = null;
private PrintWriter write = null;
private BufferedReader read = null;
public serverThread(Socket socket)
{
super("serverThread");
this.socket = socket;
}
public void run()
{
Scanner in;
in = new Scanner(System.in);
char[] input;
int inputReferance = 0;
int inputSeatAmount = 0;
boolean filmFound = false;
boolean exit = false;
try
{
read = new BufferedReader(new InputStreamReader(socket.getInputStream()));
write = new PrintWriter(new DataOutputStream(socket.getOutputStream()));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
int choice = 0;
while (exit == false)
{
choice = 0;
out.writeInt(5);
write.println("Welcome please make your selection from the options below \n 1: make a booking \n 2: cancel a booking \n 3: view available films \n 4: logout");
write.flush();
input = new char[1];
read.read(input);
choice = Integer.parseInt(new String(input));
switch (choice)
{
case 1:
{
Film tempFilm = null;
out.writeInt(1);
write.println("Please enter the referance number of the film you wish to watch");
write.flush();
read.read(input);
inputReferance = Integer.parseInt(new String(input));
for (Film s : server.filmList)
{
if (s.referanceNumber == inputReferance)
{
filmFound = true;
tempFilm = s;
}
}
if (filmFound == false)
{
out.writeInt(1);
write.println("Sorry. That referance number was not recognised. Please try again");
write.flush();
break;
}
if (filmFound == true)
{
out.writeInt(1);
write.println("Please enter the numbe rof seats you wish to book");
write.flush();
inputSeatAmount = read.read(input);
inputSeatAmount = Integer.parseInt(new String(input));
if (tempFilm.seatsAvailable < inputSeatAmount)
{
out.writeInt(2);
write.println("Sorry. There are not enough seats available for that film \n Only " + tempFilm.seatsAvailable + "seats are available");
write.flush();
break;
}
server.bookings.add(new Booking(inputReferance, server.bookingNumber, inputSeatAmount));
server.bookingNumber++;
out.writeInt(1);
write.println("booking placed successfully");
write.flush();
break;
}
}
case 2:
{
out.writeInt(1);
write.println("Please enter the booking number of the booking you wish to cancel");
write.flush();
inputReferance = read.read(input);
inputReferance = Integer.parseInt(new String(input));
for (Booking s : server.bookings)
{
if (s.bookingNumber == inputReferance)
{
filmFound = true;
break;
}
}
if (filmFound == false)
{
out.writeInt(1);
write.println("Sorry. That booking number was not recognised. Please try again");
write.flush();
break;
}
server.bookings.remove(inputReferance);
out.writeInt(1);
write.println("booking cancelled");
write.flush();
break;
}
case 3:
{
for (Film s : server.filmList)
{
out.writeInt(6);
write.println("Title :" + s.name + "\n Time : " + s.showingTime + "\n Date : " + s.day + " " + s.month + " " + s.year + "\n Price : " + s.price + "\n Referance Number : " + s.referanceNumber + "\n");
write.flush();
}
out.writeInt(1);
write.println("end of list");
write.flush();
break;
}
case 4:
{
exit = true;
out.writeInt(1);
write.println("Bye.");
write.flush();
break;
}
}
}
socket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
client code:
package syssoftclient;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Syssoftclient
{
public static void main(String[] args) throws IOException
{
try
{
InetAddress internetAddress = InetAddress.getLocalHost();
System.out.println("The address and hostname are: " + internetAddress);
System.out.println("The Hostname: " + internetAddress.getHostName());
System.out.println("The Address only: " + internetAddress.getHostAddress());
} catch (UnknownHostException e)
{
System.err.println("Connection problem " + e);
}
Socket SocketC = null;
PrintWriter out = null;
BufferedReader in = null;
boolean exit = false;
try
{
SocketC = new Socket(InetAddress.getLocalHost().getHostName(), 8888);
out = new PrintWriter(SocketC.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(SocketC.getInputStream()));
} catch (UnknownHostException e)
{
System.err.println("Host not recognised");
System.exit(1);
} catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
String fromServer = null;
String fromUser = null;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
DataInputStream din;
din = new DataInputStream(SocketC.getInputStream());
int lineCount = 0;
int linesIn = 0;
while (exit == false)
{
lineCount = 0;
linesIn = din.readInt();
while (lineCount < linesIn)
{
fromServer = in.readLine();
System.out.println("Server: " + fromServer);
lineCount++;
}
if ("Bye.".equals(fromServer))
{
System.out.println("Quitting");
exit = true;
break;
}
System.out.println("Client: ");
fromUser = stdIn.readLine(); //reads userinput
if (fromUser != null)
{
out.println(fromUser); //sends user input to the server
out.flush();
}
if ("exit".equals(fromUser))
{
exit = true;
}
}
out.close();
in.close();
stdIn.close();
SocketC.close(); //close everything before ending program
}
}

Based on your updated question, I think there error is here:
choice = Integer.parseInt(new String(input));
I'm not sure as I don't know exactly what line number 45 is.
You're trying to parse a new line character as an integer. This is throwing an exception, causing the server to exit its while loop, and the program to close.
So, wrap your parsing routines in try/catch blocks and handle them. The error should go away then.

Related

Allowing clients to talk to the server in order

I'm confused with how I'm wanting clients to talk to the server in order. For example, I'm creating a multiplayer tic tac toe game, where 2 clients will connect to the game server. The clients then take turns to put in the coordinates of the x's. However, when I use a break on my while loop, it only lets them enter once, before disconnecting the socket. How do I do it such that the clients are just temporarily blocked while the other client answers?
EDIT: I do not intend to use multithreading for this purpose.
Server (truncated for reading purposes):
try {
while (true) {
System.out.println("Awaiting connection!");
Socket clientSocket = server.accept();
System.out.println("Player " + noOfPlayers + " has connected!");
noOfPlayers ++;
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (!newGame.checkWinner()) {
out.println(newGame.currentPlayer());
input = in.readLine();
x = Integer.parseInt(input.split("\\,+")[0]);
y = Integer.parseInt(input.split("\\,+")[1]);
newGame.addPoint(x, y);
out.println("Moved");
if (newGame.checkWinner()) {
System.out.println("The winner is " + newGame.currentPlayer());
out.println("The winner is " + newGame.currentPlayer());
server.close();
break;
}
else if (newGame.boardFilledUp()) {
newGame.loadBoard();
out.println("It's a draw!");
server.close();
break;
}
newGame.loadBoard();
newGame.changePlayer();
break;
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
Client (truncated for reading purposes):
while (true) {
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
// Read input from server
BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
// Read input from client
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your coordinates in x,y form: ");
String userInput;
char serverOutput;
serverOutput = in.readLine().charAt(0);
System.out.println("Current player is " + serverOutput);
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("You sent: " + userInput);
}
break;
}
Figured out the problem. I didn't flush the PrintWriter.

send to all clients java

I have a classic client/server set up to take in a simple math problem from the client, calculate the result in the server and then send the result back to all connected clients. But on the client side it seems like I'm missing a read somewhere; the messages from first client are only returned to the second client after I input something into the second client and vice versa. I want to be able to send all messages to each client without having to input something first.
Sever code:
import java.net.*;
import java.util.*;
import java.io.*;
public class EchoServer2 extends Thread{
protected Socket clientSocket;
static String [] logs = new String[100];
private static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
static int arrayPos = 0;
static int i;
static String message;
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(10008);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2 (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally{
try{
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private EchoServer2 (Socket clientSoc){
clientSocket = clientSoc;
start();
}
public void run(){
System.out.println ("New Communication Thread Started");
try{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
writers.add(out);
BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) { //reading
logs[arrayPos] = inputLine; //keep record of all commands sent to server
arrayPos++; //update array position
if (inputLine.equals("Bye.")) //break if client enters 'Bye."
break;
if(inputLine.equals("Logs.")){ //print out contents of logs if any client enters 'Logs'
for(i=0; i<arrayPos; i++){
System.out.println("Log"+ i + ": " + logs[i]);
out.println("Log"+ i + ": " + logs[i]);
}
break;
}
int x, y, result;
String num1, num2, operator;
String [] splitStrings = inputLine.split(" ");
num1 = splitStrings[0];
x = Integer.parseInt(num1);
operator = splitStrings[1];
num2 = splitStrings[2];
y = Integer.parseInt(num2);
switch(operator){
case "+":
result = x + y;
System.out.println ("Server: " + result);
out.println(result);
for (PrintWriter writer : writers) {
if (writer == out)
continue;
writer.println(result);
}
break;
case "-":
result = x - y;
System.out.println ("Server: " + result);
out.println(result);
for (PrintWriter writer : writers) {
if (writer == out)
continue;
writer.println(result);
}
break;
case "*":
result = x * y;
System.out.println ("Server: " + result);
out.println(result);
for (PrintWriter writer : writers) {
if (writer == out)
continue;
writer.println(result);
}
break;
case "/":
result = x / y;
System.out.println ("Server: " + result);
out.println(result);
for (PrintWriter writer : writers) {
if (writer == out)
continue;
writer.println(result);
}
break;
default:
System.out.println("Please enter a more simple equation using one of the 4 main operators i.e. '+, -, *, /'");
break;
}
}
out.flush();
out.close();
in.close();
clientSocket.close();
}
catch (IOException e){
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client code:
import java.io.*;
import java.net.*;
public class EchoClient{
public static void main(String[] args) throws IOException{
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " + serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try{
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 10008);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}catch (UnknownHostException e){
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e){
System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
System.out.println("Enter a simple math equation i.e. 2 + 2 separated by a space…");
while ((userInput = stdIn.readLine()) != null){
out.println(userInput);
userInput = in.readLine();
System.out.println("echo: " + userInput);
while(in.ready()){
userInput = in.readLine();
System.out.println("echo: " + userInput);
}
System.out.println("Enter a simple math equation e.g. 2 + 2 separated by a space…");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
There's quite a few answers on this topic but none seems to work for the way I'm doing it.
All suggestions appreciated.
** I know my code isn't very elegant at the moment but at this stage it's just a case of getting it working and then tidying it up from there.
Solved
The while loop on the client side needed to be altered as so
while(true){
if(userInput == null){
System.out.println("Input is null");
}
if(userInput.equals("Bye.")){
break;
}
if(stdIn.ready()){//(userInput = stdIn.readLine()) != null){
userInput = stdIn.readLine();
out.println(clientID + "\t" + userInput);
userInput = in.readLine();
System.out.println("echo: " + userInput);
System.out.println("Enter a simple math equation e.g. 2 + 2 separated by a space…");
out.flush();
}
else if(in.ready()){
userInput = in.readLine();
System.out.println("echo: " + userInput);
//System.out.println("Enter a simple math equation e.g. 2 + 2 separated by a space…");
out.flush();
}
}
I've also made some other adjustments to the code hence why there's added variables etc!
You need to handle input and output concurrently. One option would be to use separate threads.
Right now your clients and server walk in lock step blocking on input from one to the other in sequence.
This multithreading needs to be on both the server and the client. The server will need two threads per connected client (one for input, one for output) and the clients will need the same but only for the single connection to the server.

Java socket - only works sometimes and doesn't print everything given from the server

I'm having trouble with my java client/server program using sockets. When I choose an option from the looping menu, it only works sometimes (rarely more than once), and if the output from the server has quite a few lines, the client either doesn't receive them all or doesn't print them all.
I'm very new to this, so anything would be helpful!
Client:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class client {
static String hostname = null;
static Scanner console = new Scanner(System.in);
static int myPort = 2123;
static String userChoice = null;
static String command = null;
public static void main(String[] args) throws IOException {
System.out.print("Please enter hostname: ");
hostname = console.nextLine();
if (args.length > 0)
hostname = args[0];
System.out.println ("Attemping to connect to host " +
hostname + " on port " + myPort + ".");
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket(hostname, myPort);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Can't connect to: " + hostname);
System.exit(1);
}
while(true)
{
displayMenu();
saveChoice();
if(command != null){
out.println(command);
while((in.readLine()) != null)
{
System.out.println(in.readLine());
}
}
}
}
public static void displayMenu()
{
System.out.println(" ");
System.out.println("1. Host Current Date and Time");
System.out.println("2. Host uptime");
System.out.println("3. Host memory use");
System.out.println("4. Host Netstat");
System.out.println("5. Host current users");
System.out.println("6. Host running processes");
System.out.println("7. Quit ");
System.out.println(" ");
System.out.print("Your choice: ");
userChoice = console.nextLine();
}
public static void saveChoice()
{
switch (userChoice)
{
case "1":
command = "date";
break;
case "2":
command = "systeminfo | find \"System Boot Time\"";
break;
case "3":
command = "systeminfo | find \"Virtual Memory: In Use\"";
break;
case "4":
command = "netstat";
break;
case "5":
command = "netuser";
break;
case "6":
command = "tasklist";
break;
case "7":
System.out.println("Goodbye");
System.exit(0);
break;
default:
System.out.print("That is not a choice. Please enter an option between 1-7.");
}
}
}
Server:
import java.net.*;
import java.io.*;
public class server
{
static int count = 0;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(2123);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 2123.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd /c " + inputLine);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null)
{
out.println(s);
count++;
}
System.out.print("Lines sent to client: " + count);
}
}
}

Turning a program - which writes to a file - into a GUI

my program works great and next, I want to turn it into a GUI. I have a menu:
System.out.println("Menu: ");
System.out.println("1) Enter Student Grade(s)");
System.out.println("2) View Student Grade(s)");
System.out.println("3) Delete Student Grade(s)");
System.out.println("4) Exit");
I'm not sure how to implement this into a GUI. I could maybe have 4 text fields: First name, Last name, unit and mark. I could have a button to delete, and a button to open the 'GradeEnter.txt' file perhaps. Again, I am not sure how I would implement this into a separate GUI class. Could anyone help or get me started? Thanks
Code:
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ExamGrades {
private static int menu = 0;
private static String firstName = "";
private static String firstNameDelete = "";
private static String lastName = "";
private static String lastNameDelete = "";
private static String unit = "";
private static int examMark = 0;
private static String entry = "";
private static String firstCap = "";
private static String surCap = "";
private static Scanner scan = new Scanner(System.in);
public static BufferedWriter bw;
public static BufferedReader reader;
public static PrintWriter out;
public static File deleteRecord;
public static void setup() {
reader = null;
File deleteRecord = new File("GradeEnter.txt");
try {
reader = new BufferedReader(new FileReader(deleteRecord));
} catch (FileNotFoundException e1) {
System.err.println("No file found");
}
FileWriter grades = null;
try {
grades = new FileWriter("GradeEnter.txt",true);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(grades);
out = new PrintWriter(bw);
}
public static void menuActions()
{
System.out.println("Menu: ");
System.out.println("1) Enter Student Grade(s)");
System.out.println("2) View Student Grade(s)");
System.out.println("3) Delete Student Grade(s)");
System.out.println("4) Exit");
menu = scan.nextInt();
switch(menu) {
case 1:
enterGrades();
break;
case 2:
viewGrades();
break;
case 3:
deleteGrades();
break;
case 4:
exitProgram();
break;
default:
menuActions();
}
}
public static void enterGrades()
{
System.out.print("Please enter student first name: ");
firstName = scan.next();
while(!firstName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid first name: ");
firstName = scan.next();
}
firstCap = firstName.substring(0,1).toUpperCase() + firstName.substring(1);
System.out.print("Please enter student surname: ");
lastName = scan.next();
while(!lastName.matches("[-a-zA-Z]*"))
{
System.out.print("Please enter a valid surname: ");
lastName = scan.next();
}
surCap = lastName.substring(0,1).toUpperCase() + lastName.substring(1);
System.out.print("Please select Subject Unit: ");
unit = scan.next();
System.out.print("Please enter student mark: ");
while (!scan.hasNextInt())
{
System.out.print("Please enter a valid mark: ");
scan.next();
}
examMark = scan.nextInt();
if (examMark < 40)
{
System.out.println("Failed");
}
else if (examMark >= 40 && examMark <= 49)
{
System.out.println("3rd");
}
else if (examMark >= 50 && examMark <= 59)
{
System.out.println("2/2");
}
else if (examMark >= 60 && examMark <= 69)
{
System.out.println("2/1");
}
else if (examMark >= 70 && examMark <= 100)
{
System.out.println("1st");
}
else
{
System.out.println("Invalid Mark");
}
entry = (firstCap + " " + surCap + ", " + unit + ", " + examMark);
out.println(entry);
menuActions();
}
public static void viewGrades() {
int i =1;
String line;
try {
while ((line = reader.readLine()) != null) {
System.out.println(i + ") " + line);
i++;
}
} catch (IOException e) {
System.err.println("Error, found IOException when searching for record " + e.getMessage());
}
menuActions();
}
public static void deleteGrades(){
int i = 1;
String line;
File tempFile = new File("MyTempFile.txt");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(tempFile));
} catch (IOException e) {
System.err.println("Error, found IOException when using BufferedWriter " + e.getMessage());
}
System.out.println("Current Entries Stored: ");
i =1;
try {
while ((line = reader.readLine()) != null) {
System.out.println(i + ") " + line);
i++;
}
} catch (IOException e) {
System.err.println("Error, found IOException when searching for record to delete " + e.getMessage());
}
Scanner scanner = new Scanner(System.in);
System.out.print("To delete, please enter student's First Name: ");
firstNameDelete = scanner.nextLine();
System.out.print("Now, please enter student's Surname: ");
lastNameDelete = scanner.nextLine();
try {
reader.close();
} catch (IOException e) {
System.err.println("Error, found IOException when closing closing reader: " + e.getMessage());
}
try {
reader = new BufferedReader(new FileReader(deleteRecord));
} catch (FileNotFoundException e) {
System.err.println("No file found");
}
String currentLine = "";
try {
currentLine = reader.readLine();
} catch (IOException e) {
System.err.println("Error, found IOException when reading current line " + e.getMessage());
}
while(currentLine != null) {
if(!currentLine.contains(firstNameDelete) && !currentLine.contains(lastNameDelete)) {
try {
writer.write(currentLine);
} catch (IOException e) {
System.err.println("Error, found IOException when deleting line " + e.getMessage());
}
try {
writer.newLine();
} catch (IOException e) {
System.err.println("Error, found IOException when writing a new line " + e.getMessage());
}
}
try {
currentLine = reader.readLine();
} catch (IOException e) {
System.err.println("Error, found IOException when reading file " + e.getMessage());
}
}
System.out.print("if name matches, it will be deleted ");
try {
reader.close();
} catch (IOException e1) {
System.err.println("Error, found IOException when closing reader " + e1.getMessage());
}
try {
writer.close();
} catch (IOException e) {
System.err.println("Error, found IOException when closing writer " + e.getMessage());
}
deleteRecord.delete();
tempFile.renameTo(deleteRecord);
scanner.close();
}
public static void exitProgram(){
System.out.println("Thanks for using 'GradeEnter' ");
System.exit(0);
}
public static void main(String[] args) throws Exception {
System.out.println("Welcome to the 'GradeEnter' program! ");
setup();
menuActions();
out.close();
scan.close();
reader.close();
}
}
EDIT: GradeEnter.txt looks like:
Matt Well, Computing, 100
Adam Smith, Computing, 99
Above is made up of First Name, Last Name, Course and Mark

How come readLine() is not blocking?

Given the following code, the first call to readLine() is not blocking, both "Enter name:" and "Enter address:" are printed at the same time, and address gets assigned to whatever is entered. Why? I've tried putting them in separate try blocks, getting rid of the loop and generally reordering things.
public class AddressReader {
public static void main(String[] args) {
Path file = Paths.get("d:/java IO/addresses.txt");
try {
Files.createDirectories(file.getParent());
} catch (IOException e) {
System.err.println("Error craeting directory: " + file.getParent());
e.printStackTrace();
System.exit(1);
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int c = 0;
try {
System.out.println("<a>dd an entry or <r>ead entries");
c = br.read();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
switch (c) {
case 'a':
String name = null;
String address = null;
while (name == null || name == "" || address == null || address == "") {
try {
System.out.println("Enter name:");
name = br.readLine();
System.out.println("Enter address:");
address = br.readLine();
} catch (IOException e) {
System.out.println("An error has occured, try again");
}
System.out.println("name = " + name);
System.out.println("address = " + address);
}
//writeEntry(file, name, address);
break;
case 'r':
//readEntries(file);
break;
default:
System.out.println("Invalid entry, try again.");
}
}
}
This is because of this line:
c = br.read();
This does not consume the new-line character that is produced by pressing ENTER.
To solve this issue, use this instead:
c = br.readLine().charAt(0);
Over and above whats already been said, for what you're trying to do I suggest using the Console instead:
Console console = System.console();
String name = console.readLine("Create a name.");
char[] password = console.readPassword("Create a password.");
System.out.println(name + ":" + new String(password));

Categories