I keep getting "java.lang.IllegalStateException" after using Scanner()
this is what I have
public void insertBook(){ //this method allows the user to insert a new book in the database
Boolean select = false;
Scanner input = new Scanner(System.in);
File textFile = new File("src/newbooks.txt");
FileWriter fw = null; //FileWriter and BufferedWriter have to be initialized and used inside a try catch
//to be used outside, initialize the objects as null
BufferedWriter bw = null;
try{
fw = new FileWriter(textFile);//check if it can read the textfile
bw = new BufferedWriter(fw);//FileWriter has to be wrapped in BufferedWriter
}catch(IOException e){
System.out.println("the file could not be found");
}//end catch
System.out.println(" select is " +select);//if(text == "n")
System.out.println("enter the book information below");
System.out.println("if the informatin is not available, enter\"information not available\"");
System.out.print("do you wnat to enter a book? ");
String text = input.next();
if(text.equals("n"))
select = true;
do{
String book = new String();
if(select == true)
break;
if(text.equals("n")){
System.out.print("inside if no\n");
select = true;
//break;//break here so
}
else if (text.equals("y")){
System.out.println("inside if y");
try{
Scanner input2 = new Scanner(System.in);
System.out.print("enter the title of the book: ");
book = input2.next();
bw.write(book + ", ");
System.out.println("after first write");
System.out.print("enter the author: ");
book = input2.next();
bw.write(book + ", ");
System.out.println();
System.out.print("enter the year of the book: ");
book = input2.next();
bw.write(book + ", ");
System.out.println();
System.out.print("enter the gender: ");
book = input2.next();
bw.write(book + ", ");
//System.out.println();
System.out.print("enter a description: ");
book = input2.next();
bw.write(book + ", ");
System.out.println();
bw.write("\n");
input2.close();
select = false;
}
catch(IOException e){
System.out.println("the text could not be read");
}
input.close();
}
else{
System.out.println("you didn't enter a valid selection");
}
System.out.print("do you want to enter another booK? Enter y for yes and n for no");
text = input.nextLine(); //error here
if(text.equals("n"))
select = true;
}while(select == false);//end while select
//input.close();
}//end of insert method
whenever I try to use the Scanner outside the if statements, it gives met the same error. it works if I enter a wrong choice or "n", but if I choose "y" and enter the data the Scanner fails after it gets to the last line for the input inside the do-while loop.
...
bw.write("\n");
input2.close();
select = false;
}
catch(IOException e){
System.out.println("the text could not be read");
}
You close the scanner here:
input.close(); // <- remove this line
}
else{
System.out.println("you didn't enter a valid selection");
}
...
And here it is already closed.
...
text = input.nextLine();
if(text.equals("n"))
select = true;
...
Close your scanner after you last need it.
This is because you cannot request a new line from a closed scanner.
Read more about it in the API Documentation about scanner:
public void close()
Closes this scanner. If this scanner has not yet
been closed then if its underlying readable also implements the
Closeable interface then the readable's close method will be invoked.
If this scanner is already closed then invoking this method will have
no effect.
Attempting to perform search operations after a scanner has been
closed will result in an IllegalStateException.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()
Related
Hello everyone i'm doing my homework and i want to understand, how to fulfill properly third section in code - 3.View operation history. (List of all operations performed by user, use array for storing this information in format: “[operation index]. [operation name] - [user input]”. Also i have an issue -
Application should work and accept user input until he wants to exit from program.
Scanner in = new Scanner(System.in);
System.out.println("Please select operation");
System.out.println("1.Encode");
System.out.println("2.Decode");
System.out.println("3.View operation history");
System.out.println("4.Exit program");
Integer userInput = Integer.valueOf(in.nextLine());
if (userInput.equals(1)) {
System.out.println("You chosen encoding operation");
System.out.println("Please choose codec name - caesar or morse");
String userInputEncode = in.nextLine().toLowerCase();
if (userInputEncode.equals("caesar")) {
System.out.println("Enter text to encode");
String userInputEncode2 = in.nextLine().toLowerCase();
System.out.println("Encoded text: " + caesarEncoder.encode(userInputEncode2));
} else if (userInputEncode.equals("morse")) {
System.out.println("Enter text to encode");
String userInputEncode3 = in.nextLine().toLowerCase();
System.out.println("Encoded text: " + morseEncoder.encode(userInputEncode3));
} else
System.out.println("You entered wrong codec name, try one more time");
} else if (userInput.equals(2)) {
System.out.println("You chosen decoding operation");
System.out.println("Please choose codec name - caesar or morse");
String userInputDecode = in.nextLine().toLowerCase();
if (userInputDecode.equals("caesar")) {
System.out.println("Enter text to decode");
String userInputDecode2 = in.nextLine().toLowerCase();
System.out.println("Decoded text: " + caesarDecoder.decode(userInputDecode2));
} else if (userInputDecode.equals("morse")) {
System.out.println("Enter text to Decode");
String userInputDecode3 = in.nextLine().toLowerCase();
System.out.println("Decoded text: " + morseDecoder.decode(userInputDecode3));
}
else
System.out.println("You entered wrong codec name, try one more time");
}
else if (userInput.equals(3)) {
}
else if (userInput.equals(4)) {
in.close();
System.out.println("Program was closed by user");
You probably need a loop that checks if the user has typed the number 4.
Then you can create a List before the loop where you will store all the history of what the user has typed during the execution of the program.
And then in the case of the number 3 is selected, you can use that list to take the historical data and then print all the data that you need
Below a simple and fast example (not the best way):
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
Scanner in = new Scanner(System.in);
List<String> operationHistory=new ArrayList<String>();
Integer userInput = null;
do{
System.out.println("Please select operation");
System.out.println("1. aaa");
System.out.println("2. bbb");
System.out.println("3. print selection history");
System.out.println("4. exit");
userInput = Integer.valueOf(in.nextLine());
if (userInput.equals(1)) {
System.out.println("Please type something");
String userInputEncode = in.nextLine().toLowerCase();
operationHistory.add("1. aaa - " + userInputEncode);
}else if (userInput.equals(2)) {.
System.out.println("Please type something");
String userInputEncode = in.nextLine().toLowerCase();
operationHistory.add("2. bbb - " + userInputEncode);
}else if (userInput.equals(3)) {
System.out.println("Operation History:");
for(String operationitem:operationHistory){
System.out.println(operationitem);
}
System.out.println("-------------");
}
}while(!userInput.equals(4));
in.close();
System.out.println("Program was closed by user");
This is just an example similar to your code, you can use it to understand how your problem can be solved and how the loops and the lists works
You then probably want to manage some unexpected input
I'm trying to write a program which will take user input from a list of options then either:
write to a file
alter an existing file or
delete a file.
At the moment I'm stuck on just writing to the file from the user input. I have to use regex notation for each of the users input as seen in the snippet. Any help or guidance on what i could do will be highly appreciated, and yes there are a lot of errors right now. Thanks!
import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
private UserInput[] list;
class Input {
public static void main(String[] args) {
Scanner in = (System.in);
string Exit ="False";
System.out.println("person details");
System.out.println("");
System.out.println("Menu Options:");
System.out.println("1. Add new person");
System.out.println("2. Load person details ");
System.out.println("3. Delete person Entry");
System.out.print("Please select an option from 1-5\r\n");
int choice = in.nextLine();
if (choice == 1)
system.out.println("you want to add a new person deails.");
AddStudnet();
else if (choice == 2){
system.println("would you like to: ");
system.println("1. Load a specific entry");
system.println("2. Load ");
}
//Error checking the options
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int input = Integer.parseInt(br.readLine());
if(input < 0 || input > 5) {
System.out.println("You have entered an invalid selection, please try again\r\n");
} else if(input == 5) {
System.out.println("You have quit the program\r\n");
System.exit(1);
} else {
System.out.println("You have entered " + input + "\r\n");
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your input!\r\n");
System.exit(1);
}
}
}
//Scanner reader = new Scanner(System.in);{ // Reading from System.in
//System.out.println("Please enter your name: ");
//String n = reader.nextLine();
//}
// File file = new File("someFile.txt", True);
// FileWriter writer = new FileWriter(file);
// writer.write(reader);
// writer.close();
public static void addPerson(String args[]) throws IOException{
class input Per{
scanner in = new scanner (system.in);
system.out.print("Please enter you Name: ");
String name = in.nextLine()
final Pattern pattern = Pattern.compile("/^[a-z ,.'-]+$/i");
if (!pattern.matcher(name).matches()) {
throw new IllegalArgumentException("Invalid String");
//String Name = regex ("Name")
//regex below for formatting
system.out.println("Please enter your Job title:");
//String CourseNum = regex ("JobTitle");
system.out.println("Please enter your Town:");
//String Town = regex("Town");
system.out.println("Please enter your postcocde:");
//String postcocde = regex("postcocde");
system.out.println("Please enter your street:");
//String Street = regex ("Street");
system.out.println("Please enter your House Number:");
//String HouseNum = regex ("HouseNum");
}
}
//public static void
Is not clear that you look for " i'm stuck on just writing to the file"
here exemple on how to create/write to a file
String export="/home/tata/test.txt";
if (!Files.exists(Paths.get(export)))
Files.createDirectory(Paths.get(export));
List<String> toWrite = new ArrayList();
toWrite.add("tata");
Files.write(Paths.get(export),toWrite);
look at java tm
https://docs.oracle.com/javase/tutorial/essential/io/file.html
lio
We have managed to get the code to display the first employee's details, however, the other 2 employee details have it been displayed. I am not sure how to append them. I am not sure if the printWriter is the right thing to out put the code and of not then, what would be best?
The code is below :)
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner(System.in);
File employeeDetails = new File("Employees.txt");
PrintWriter pw = new PrintWriter(new FileWriter(employeeDetails, true));
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);
try{
boolean repeat = false;
System.out.println("Enter name: ");
String name = scan.next();
pw.println("name: " + name);
System.out.println("Enter job title: ");
String jobTitle = scan.next();
pw.println("Job title: " + jobTitle);
do{
try{
System.out.println("Enter age: ");
int age = scan.nextInt();
pw.println("Age: " + age);
repeat = true;
}
catch(InputMismatchException ex){
System.err.println("Invalid age please enter a whole number.");
scan.next();
continue;
}
}while(repeat==false);
do{
try{
System.out.println("Enter salary per year: ");
double salary = scan.nextDouble();
pw.println("Salary: " + salary);
repeat = false;
}
catch(InputMismatchException ex){
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
catch(MissingFormatArgumentException ex){
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
}while(repeat);
}finally{
pw.close();
fw.close();
}
}
scan.close();
}
}
So you problem is that each time in for loop you create a new file(deleting the other)
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);
put it outside
You don't need fw:
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);// remove this line
...
and also remove this line:
fw.close();
otherwise you'll get NullPointerException
Your problem is that you keep closing pw. Move the close of pw after the for loop. I have modified your code and the following works:
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
File employeeDetails = new File("Employees.txt");
PrintWriter pw = new PrintWriter(new FileWriter(employeeDetails, true));
for (int i = 0; i < 3; i++) {
//FileWriter fw = new FileWriter("Employees.txt", true);
try {
boolean repeat = false;
System.out.println("Enter name: ");
String name = scan.next();
pw.println("name: " + name);
System.out.println("Enter job title: ");
String jobTitle = scan.next();
pw.println("Job title: " + jobTitle);
do {
try {
System.out.println("Enter age: ");
int age = scan.nextInt();
pw.println("Age: " + age);
repeat = true;
} catch (InputMismatchException ex) {
System.err.println("Invalid age please enter a whole number.");
scan.next();
continue;
}
} while (repeat == false);
do {
try {
System.out.println("Enter salary per year: ");
double salary = scan.nextDouble();
pw.println("Salary: " + salary);
repeat = false;
} catch (InputMismatchException ex) {
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
} catch (MissingFormatArgumentException ex) {
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
} while (repeat);
} finally {
//pw.close();
//fw.close();
}
}
pw.close();
scan.close();
}
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWritingApp{
public static void main(String[] args) {
String inputFilename = "marks.txt"; // It expects to find this file in the same folder as the source code
String outputFilename = "fakemarks.txt"; // The program will create this file
PrintWriter outFile;
String name,choice;
int mark1,mark2;
boolean flag=false;
Scanner input = new Scanner(System.in);
System.out.println("Do you want to add or find a student?");
try {
outFile = new PrintWriter(new FileWriter(outputFilename),true); // create a new file object to write to
File file = new File(inputFilename); // create a file object to read from
File file1 = new File(outputFilename);
Scanner scanner = new Scanner(file); // A scanner object which will read the data from the file passed in.
choice= input.nextLine();
switch(choice){
case "f":
System.out.println("Enter a name:");
name=input.nextLine();
while (scanner.hasNextLine()) { // This will loop until there are no more lines to read
String line = scanner.nextLine();
if(line.contains(name)){
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
line=name+", " + mark1 +", "+ mark2;
outFile.println(line);
flag=true;
} else {
outFile.println(line);
}
}
if(flag==false){
System.out.println('"'+name+'"'+" wasn't found");
}
break;
case "a":
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
outFile.println(line);
}
System.out.println("Enter a name:");
name=input.nextLine();
System.out.println("Enter the first mark set:");
mark1=input.nextInt();
System.out.println("Enter the second mark set:");
mark2=input.nextInt();
outFile.println(name+", " + mark1 +", "+ mark2);
break;
}
***scanner.close();
outFile.close();
if(file1.renameTo(file)){
System.out.println("rename succesful");
} else {
System.out.println("rename unsuccesful");
}
if(file.delete()){
System.out.println("delete succesful");
} else {
System.out.println("delete unsuccesful");
}***
}catch (IOException e) {
e.printStackTrace();
}
}
}
What I am having a problem with is that every time I run the program it returns false for changing the name of the new file to the original file and deleting the original file itself. I would appreciate if someone posted some code to solve this. I have highlighted the code that outputs feedback above.
Sorry for the lengthy code below, my code is able to execute and run properly when user input option '5'. I have already get all the values from user input and there is no error, but it did not write to my file.
My file currently has data in it:
Anthony Ducan;anthony;a123;55 Peter Street;3321444;VISA;3213504011223
Barry Blake;barry;a999;456 George Street;23239876;VISA;435677779876
Claire Rerg;clare;c678;925 Edward Lane;67893344;MASTERCARD;223344556677
I am trying to store the exact same way as my textfile.
Is there something wrong with my coding at void writeLinesToFile() method or is it the void newCust() method?
Still puzzled that I have no errors but it is not writing to my file.
public MainPage1(){ //start of MainPage1()
System.out.println("=====================================================");
System.out.println("Kreg Hotel Booking System - Main Page");
System.out.println("=====================================================");
System.out.println("[1] General Information");
System.out.println("[2] Make Booking");
System.out.println("[3] Active Booking Summary");
System.out.println("[4] Existing Customer");
System.out.println("[5] New Customer");
System.out.println("[6] Check Booking Status");
System.out.println("[7] Promotions");
System.out.println("[8] Exit\n");
System.out.println("Note: You have to select option 2 & 3 before option 4 & 5\n");
System.out.println("Please enter your selection: ");
try{choice = input.nextInt();}//to try to see if user input integer
catch (java.util.InputMismatchException e){//to catch if user didnt input integer
System.out.println("Invalid Input");
return;
}
while(true){ //start of do-while loop
if(choice==4||choice==5)
{
if(roomInfo.isEmpty()==true || addOns.isEmpty()== true){
System.out.println("Please enter option 2 or 3 before option 4 or 5");
choice=input.nextInt();
}
else if(choice == 4){existingCustomers();}
else if(choice ==5){newCust();}
else new MainPage1();
}
switch(choice){
case 1:break;
case 2:break;
case 3:break;
case 4:break;
case 5:newCust();
break;
case 6:break;
case 7:break;
case 8:System.out.println("Thank you. See you again soon");//exit the menu
System.exit(0);break;
default:System.out.println("Please enter number between 1 to 8");//prompts the user if they didnt enter between 1 to 8
choice = input.nextInt();
break;
}
}//while(choice!=1 || choice !=2 || choice!=3 ||choice!=4); // end of do-while loop
}//end of MainPage1()
public static void main(String[] args){//start of main page
new MainPage1();//to call the constructor
}//end of mainpage
public void writeLinesToFile(String filename,String[] linesToWrite,boolean appendToFile){
PrintWriter pw = null;
try {
if (appendToFile) {
//If the file already exists, start writing at the end of it.
pw = new PrintWriter(new FileWriter(filename, true));
}
else {
pw = new PrintWriter(new FileWriter(filename));
//this is equal to:
//pw = new PrintWriter(new FileWriter(filename, false));
}
for (int i = 0; i < linesToWrite.length; i++) {
pw.println(linesToWrite[i]+";");
}
pw.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
//Close the PrintWriter
if (pw != null)
pw.close();
}
}
public void newCust(){
System.out.println("Welcome to Kreg Hotel Booking System");
System.out.println("==============================================");
System.out.println("Please enter your name: ");
n = input.nextLine();
n = input.nextLine();
System.out.println("Please enter your login username: ");
un = input.nextLine();
System.out.println("Please enter your login password: ");
pw = input.nextLine();
System.out.println("Please enter your address: ");
a = input.nextLine();
System.out.println("Please enter your contact: ");
con = input.nextLine();
System.out.println("Please enter your credit card type: ");
ct = input.nextLine();
System.out.println("Please enter your credit card number: ");
cn = input.nextLine();
MainPage1 util = new MainPage1();
util.writeLinesToFile("customerinfo.txt",new String[]{n,un,pw,a,con,ct,cn},true);
new MainPage1();
}
}//end of class
Have a look at File, BufferedWriter and FileWriter docs. You should be able to accomplish this with those two class. This code should get you started.
String content = "Add this everytime";
File file =new File("example.txt");
//if file does not exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(content);
bufferWritter.close();
System.out.println("Done");