How come readLine() is not blocking? - java

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));

Related

Make a loop AND catch using Strings instead of ints? (java)

I'm trying to make a text based rock paper scissors. I want the player to choose what they want to play to, for example "best (user response/2 + 1) out of (user response)" then it asks for verification if they would like to play to that number. If they say yes it continues the game with that score, if no it loops back up and lets them choose another number and I have an else that reminds them they can either select yes or no. When they are originally asked, letters don't effect and they are asked to try again. On the second loop around (when you say no) if you enter a String instead of an Int it crashes. Here what I have.
System.out.println("Best of:");
String line = userIn.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
bestOf = Integer.parseInt(line);
break;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = userIn.nextLine();
}
System.out.println("Okay, so you want to play best " + (bestOf / 2 + 1) + " of " + bestOf + "?");
String response2 = userIn.nextLine();
while (true) {
if (response2.contains("n")) {
System.out.println("What do you wish to play to then, " + name + "?");
bestOf = userIn.nextInt();
response2 = "y";
} else if (response2.contains("y") || response2.contains("Y")) {
winScore = (bestOf / 2 + 1);
System.out.println("Okay, best " + (bestOf / 2 + 1) + " of " + bestOf + " it is!");
break;
} else {
System.out.println("That's not a valid response! Try again.");
response2 = userIn.nextLine();
}
}
Instead of using parseInt use the string, in other words the input take it as string (even if is a number) them use the function "isNumber" too check if the string the user put is a number if not, do a while
System.out.println("Best of:");
String line = userIn.nextLine();
String aux = line;
do{
if (line.length() > 0)
aux = line;
if(!isNumeric(aux)){
System.out.println("Please enter a number");
line = userIn.nextLine();
}
}while(!isNumeric(aux));
bestOf = Integer.parseInt(aux);
so
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
You can extract your loop as a method and use it in second case as well.
private Integer readInt(Scanner scanner){
String line = scanner.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
Integer result = Integer.parseInt(line);
return result;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = scanner.nextLine();
}
}
or even better:
private Integer readInt(Scanner scanner){
Integer result;
do{
try{
return scanner.nextInt();
} catch (InputMismatchException e){
scanner.nextLine();
System.out.println("Please enter a number");
}
} while (true);
}

Need to output Strings to a .txt file

I'm at my wits end here, me and a friend have been trying to get user input and write that to a .txt file but I have no idea where I'm gone wrong...
public static void main (String [] args)
{
toTxtFile();
}
static void toTxtFile()
{
//Scanner in = new Scanner (System.in);
try
{
File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
records.createNewFile();
FileWriter fw = new FileWriter(records, true);
PrintWriter pw = new PrintWriter(fw);
String str = JOptionPane.showInputDialog(null,"Enter your text below");
str = str.toUpperCase();
pw.println(str);
if (str.length() == 3 && str.contains("END"))
{
JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
pw.flush();
pw.close();
//in.close();
}
else
{
pw.println(str);
toTxtFile();
}
}
catch (IOException exc)
{
exc.printStackTrace();
}
}
}
I've tried putting the loop as a do/while with far from good results, any help would be appreciated D:
You can use a try-with-resources to close when you're done; and you might use an infinite loop with a break like
static void toTxtFile() {
File records = new File("C:\\Users\\rodriscolljava\\Desktop\\IOFiles\\test3.txt");
try (PrintWriter pw = new PrintWriter(records)) {
while (true) {
String str = JOptionPane.showInputDialog(null, "Enter your text below");
str = str.toUpperCase();
if (str.equals("END")) {
JOptionPane.showMessageDialog(null, "You've ended the task",
"ERROR", JOptionPane.ERROR_MESSAGE);
break;
}
pw.println(str);
}
} catch (IOException exc) {
exc.printStackTrace();
}
}
you have to add ,
pw.flush();
after pw.println(str);
and want to do it again and again then put it into while loop likewise,
while(true){
String str = JOptionPane.showInputDialog(null,"Enter your text below");
str = str.toUpperCase();
if (str.length() == 3 && str.contains("END"))
{
JOptionPane.showMessageDialog(null, "You've ended the task","ERROR",JOptionPane.ERROR_MESSAGE);
break;
}
pw.println(str); // else write to file...
pw.flush();
}
pw.flush();
pw.close();

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

BufferedReader in java, always throws exception

public static void main (String[] args) {
try{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println ("1..case1 | 2..case2");
String ch=Integer.parseInt(bf.readLine()); //user input for switch
System.out.println (ch);
bf.close();
switch(ch) { //userinput ch variable switch in case
case 1 :
String data=bf.readLine();
bf.close();
System.out.println(data);
break;
case 2 :
System.out.print ("Enter Key ");
String key=bf.readLine();
bf.close();
System.out.println(key);
break;
default :
System.out.println ("wrong choice");
}
}
catch(IOException e){
System.out.println ("io error");
}
bf.close();
}
//every time after 1st user input it goes to partcular matching case, but at the next user input it throws an exception.
please help..
thanks in advance..
Its a good habit to close in finally block else use try with resource if you are using java7 or higher version
See this mkyongs example
Also this line is wrong String ch=Integer.parseInt(bf.readLine()); make it to int
you are converting bf.readLIne() to int and storing in string,This is wrong.
Another error is you are closing bf.close(); after the try-catch block so compiler may complain
Complete working code
public static void main (String[] args) {
BufferedReader bf=null;
try{
bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println ("1..case1 | 2..case2");
int ch=Integer.parseInt(bf.readLine()); //user input for switch
System.out.println (ch);
switch(ch){ //userinput ch variable switch in case
case 1 :
String data=bf.readLine();
System.out.println(data);
break;
case 2 :
System.out.print ("Enter Key ");
String key=bf.readLine();
System.out.println(key);
break;
default :
System.out.println ("wrong choice");
}
} catch(IOException e){
System.out.println ("io error");
e.printStackTrace();
}
finally
{
try {
bf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

java client-server program crashes after first iteration through loop

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.

Categories