Java - create an instance of file reader and output - java

I have a program which reads some data under a file reader and then creates an instance of another class which models the data. Anyway that class works (has been tested with some hard coded values) but I now want to output the data of the instance of a Patient being read under the file reader but seem unable to.
Could anyone tell me where i'm going wrong.

You are not adding Patient instances to newPatient collection, that's why it's empty and you are not getting anything printed out. Add elements to queue:
while(scan.hasNextLine()){
String firstname = scan.nextLine();
String surname = scan.nextLine();
String illness = scan.nextLine();
int illnessSeverity = scan.nextInt();
String newLine = scan.nextLine();
newPatient.add(new Patient(firstname,surname,illness,illnessSeverity));
for (Patient newPatientData : newPatient) {
System.out.println(newPatientData);
}

You need to add data first to the Priority Queue. I think you missed that .
PriorityQueue<Patient> newPatient = new PriorityQueue<>();
File fileName = new File("patients.txt");
Scanner scan = null;
try {
scan = new Scanner(fileName);
while(scan.hasNextLine()){
String firstname = scan.nextLine();
String surname = scan.nextLine();
String illness = scan.nextLine();
int illnessSeverity = scan.nextInt();
String newLine = scan.nextLine();
Patient newP = new Patient(firstname,surname,illness,illnessSeverity);
newPatient.add(newP);
}
for (Patient newPatientData : newPatient) {
System.out.println(newPatientData);
}
} catch(Exception e) {
System.out.println("ERROR - file not found");
}

Related

How can I take a String with a name and two values and separate it into a String containing the name and 2 doubles containing the values?

I've written a class for a program designed to help manage a volleyball team's roster. The roster is contained in a .dat file and the players are written as follows:
Rachael Adams 3.36 1.93
My issue arises when I try to separate this string into the proper data types (the name being a string, then the first and second values being doubles for the stats).
public Roster(String filename) {
players = new ArrayList<Player>();
try {
FileReader fr = new FileReader(filename);
BufferedReader inFile = new BufferedReader (fr);
String line = inFile.readLine();
Scanner scan = new Scanner(line);
while(line != null) {
String firstName = scan.next();
String lastName = scan.next();
double attackStat = scan.nextDouble();
double blockStat = scan.nextDouble();
String name = firstName + " " + lastName;
Player newPlayer = new Player(name, attackStat, blockStat);
players.add(newPlayer);
line = inFile.readLine();
}
scan.close();
inFile.close();
} catch (IOException e) {
System.out.println(e);
}
}
The program throws this exception when a Roster object is created
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at Roster.<init>(Roster.java:30)
at Assignment08.openRosterFile(Assignment08.java:59)
at Assignment08.main(Assignment08.java:18)
I am newer to Java and still facing a learning curve, so if there is more information needed then please let me know.
If at all possible, I would greatly appreciate an explanation as to what I did wrong rather than just a solution. Thank you very much.
I always find it easier to split the line:
String[] columns = line.split(" (?=\\d)";
String name = columns[0];
double attackStat = Double.parseDouble(columns[1]);
double blockStat = Double.parseDouble(columns[2]);
This works by splitting on a space, but only when the next char is a digit via the look ahead (?=\d).
This automatically caters for any number of words in the name.

Reading Text File into Array using Java generates Exception

Even though the file Movie_db.txt isn't empty, I get the following exception:
the text file consists of this:
hank horror 20.0 18 1
public void syncDB(List<Movie> movieList) throws IOException {
Scanner scanner = new Scanner("Movie_db.txt");
BufferedReader reader = null;
try {
String line = null;
String title;
String genre;
double movieDuration;
int ageRestriction;
int id;
while (scanner.hasNext()) {
title = scanner.next();
genre = scanner.next();
movieDuration = scanner.nextDouble();
ageRestriction = scanner.nextInt();
id = scanner.nextInt();
movieList.add(new Movie(title, genre, movieDuration, ageRestriction, id));
}
} catch (Exception e) {
System.out.println("List is empty");
}
}
Considering your path is correct, there is a problem in your code. I'd change this line
Scanner scan = new Scanner("Movie_db.txt");
with this one
Scanner scan = new Scanner(Paths.get("Movie_db.txt"));
The reason is that in your snippet the Scanner only reads the string "Movie_db.txt" and in the second snippet it recognizes as the path to file.
Read Scanner documentation for more info
genre = scan.next(); line is throwing exception because nothing is left to read from file now, which causes catch block to execute.
You are providing a string to Scanner which is a valid input for scanner. Hence, it never reads the file.
Scanner scan = new Scanner(new File("full_path_to_container_dir/Movie_db.txt"));
Please have a look at this blog on how to read from a file using scanner - https://www.java67.com/2012/11/how-to-read-file-in-java-using-scanner-example.html.

How can i make string save into a text file only if it starts with !test?

try {
Scanner Majora = new Scanner(System.in);
System.out.println("what is your name?");
String Link = Majora.nextLine();
Scanner Lenk = new Scanner(System.in);
System.out.println("name of file?");
String Lunk = Lenk.nextLine();
if(Link.equalsIgnoreCase("!addcom");
File ocarina = new File("/Users/Unknown/Desktop/commands/" + Lunk + ".txt");
if (ocarina.exists()) {
ocarina.createNewFile();
}
FileWriter Majoras = new FileWriter(ocarina.getAbsoluteFile());
BufferedWriter Zelda = new BufferedWriter(Majoras);
Zelda.write(Link);
Zelda.close();
}
this is what i got so far :/
i need help on making it like if a certain word is used before the string you wanna save. save the string.
use startswith string method
if(Link.startsWith("!test"))
Zelda.write(Link);
substring will get you the string without !test which is 5 characters
Link = Link.substring(5);

Input Mismatch Exception Error,

Program compiles and runs perfectly until I try to execute my load method in main. Program crashes and gives me an input mismatch exception at
part number = scan.nextInt(); ..... Anyone know why?
public static InventoryManager load(String fileName) throws IOException,ClassNotFoundException
{
Scanner fileScan = new Scanner (new File(fileName));
Scanner stringScan;
InventoryManager StockChart = new InventoryManager();
// Part variables
String record = "";
int partNumber=0;
String description="";
int qty=0;
double cost = 0.00;
while(fileScan.hasNext())
{
record = fileScan.nextLine();
stringScan = new Scanner (record);
stringScan.useDelimiter(" "); //allows for separation when reading
partNumber = stringScan.nextInt(); // scans part number
description = stringScan.next(); // scans description
qty = stringScan.nextInt(); // scans the qty on hand
cost = stringScan.nextDouble(); // scans the item cost
//create new part object for each line in file
StockChart.addStock(new Stock(partNumber,description, qty,cost));
}
return StockChart; // return new list back to InventoryClerk program
}
Text File is formatted as follows (disregard spaces in between):
1117[tab]1/2-13 FHN[tab]450[tab]6.11
1118[tab]1/2-13 FHN[tab]100[tab]0.23
1119[tab]1/2-13 FHN[tab]100[tab]4.11
A better way rather than using the stringScan Scanner object is to simply to use String.split on the record String
e.g.
while(fileScan.hasNext())
{
record = fileScan.nextLine();
String el[] = record.split (" ");
partNumber = Integer.parseInt (el[0]);
description = el[1];
// etc

Java Delete a line from txt after reding the file [duplicate]

This question already has answers here:
Java - delete line from text file by overwriting while reading it
(3 answers)
Closed 8 years ago.
I have this file
1007 book1 5 3
1004 book2 4 1
1003 book3 3 0
1002 book4 2 1
and I am trying to delete the book number 1004 from the file, but before that I let the user enter the number of the book that he wants to delete.
First check if the book exists in the file or not, if the book is exists I delete it if not show "the book does not exists".
Scanner kb = new Scanner(System.in);
FileInputStream book = new FileInputStream("input.txt");
Scanner infile = new Scanner(book);
FileOutputStream out = new FileOutputStream("output.txt");
PrintWriter pw = new PrintWriter(out);
boolean found = false;
System.out.print("Enter the bookID : ");
int bID = kb.nextInt();
while(infile.hasNext()){
int id = infile.nextInt();
String title = infile.next();
int quantity = infile.nextInt();
int bQuantity = infile.nextInt();
if(bID == id){
found = true;
}
if(found == true){
pw.printf("%8d\t%-30s\t%8d\t%8d", infile.nextInt(), infile.next(), infile.nextInt(), infile.nextInt());
infile.nextLine();
System.out.println("The book has been deleted");
break;
}
}
if(found == false)
System.out.print("Not found");
pw.close();
infile.close();
I am trying to print all the file with out the book I have deleted.
You will need a book class, like this:
public class Book {
private int series;
private String name;
private int intA;
private int intB;
public Book(int series,String name, int intA, int intB) {
this.series = series;
this.name = name;
this.intA = intA;
this.intB = intB;
}
....
.... (add other methods as needed, you will definitely need a
toString() method, and getIntA(), getIntB(), getSeriesNum(),
getName() etc.)
}
When you use scanner to read the file, read them into an arraylist of type Book. When user enter a number, use a for loop to find the Book that matches that number, and remove that book object from your arraylist.
Also, try to keep data in memory and not write files too often. Writing files to disks is very inefficient comparing with changing data in memory. Once user is done with all his/her operations, you can use a printwriter to write the data to your file.
To read your file into this array of objects, you can do this:
public static ArrayList<Book> readbooklist() {
ArrayList<Book> booklist = new ArrayList<Book>();
File file = new File("path/filename.fileextension");
try {
Scanner scnr = new Scanner(file);
while (scnr.hasNextLine()) {
String entry = scnr.nextLine();
String [] parts = entry.split("\t"); // Depends on how data was delimited
int series = Integer.parseInt(parts[0]);
int intA = Integer.parseInt(parts[2]);
int intB = Integer.parseInt(parts[3]);
Book single = new Book(series, parts[1], intA, intB);
booklist.add(single);
}
scnr.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found!");
}
return booklist;
}
Remember to import proper dependency at the beginning of your class. Wish it helps!
I'd recommend to use a Map to store each line as value and the Id as the key only once. That way you don't have to reopen the file and read it each time you want to remove or add an entry, all you have to do is remove it and add it to the map. Once you are done, you can overwrite the old file you have by the values stored in the map or just create a new temp file to hold the data, delete the old file and then rename the temp file with old file's name
Store all the lines you would like to save in a String and close the scanner. Create a printwriter, print the string to the file and close it.
Example code:
File file = new File("yourTextFile.txt");
Scanner in = new Scanner(file);
String saveThisToFile = "";
while (in.hasNext()) {
String temp = in.nextLine();
if (condition to be true if you whant to keep this line) {
saveThisToFile += temp + "\n";
}
}
in.close();
PrintWriter printWriter = new PrintWriter(file);
printWriter.print(saveThisToFile);
printWriter.close();

Categories

Resources