Only output partial result with PrintStream - java

Please take a look at my code.
import java.util.*;
import java.io.*;
public class LibraryDriver {
public static void main(String[] theArgs) {
String theAuthor = "";
String theTitle = "";
Scanner input = null;
PrintStream output = null;
try {
input = new Scanner(new File("LibraryIn1.txt"));
output = new PrintStream(new File("LibraryOut.txt"));
} catch (Exception e) {
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
ArrayList < String > authors = new ArrayList < String > ();
ArrayList < Book > books = new ArrayList < Book > ();
while (input.hasNext()) {
// Read title
theTitle = input.nextLine();
// Read author(s)
theAuthor = input.nextLine();
authors = new ArrayList < String > (getAuthors(theAuthor));
// Insert title & author(s)into a book
// Add this book to the ArrayList<Book> of books
books.add(new Book(theTitle, authors));
authors.clear();
}
// Instantiate a Library object filled with the books read thus far
// and write the contents of the library to the output file
Library lib = new Library(books);
output.println("PRINTS INITIAL BOOK LIST:");
output.println(lib);
// Sort the current contents of the library
lib.sort();
// and write the contents of the sorted library to the output file
output.println("\nPRINTS SORTED BOOK LIST:");
output.println(lib);
// Close the first input file and open the second input file.
// Read the titles and authors from the second input file,
// add them to the library, and write the contents of the
// library to the output file.
input.close();
try {
input = new Scanner(new File("LibraryIn2.txt"));
output = new PrintStream(new File("LibraryOut.txt"));
} catch (Exception e) {
System.out.println("Difficulties opening the file! " + e);
System.exit(1);
}
while (input.hasNext()) {
theTitle = input.nextLine();
theAuthor = input.nextLine();
authors = (getAuthors(theAuthor));
Book b = new Book(theTitle, authors);
lib.add(b);
}
output.println("\nPRINT WITH NEW BOOK UNSORTED:");
output.println(lib);
// Sort the library and write it to the output file
lib.sort();
output.println("\nPRINT ALL SORTED BOOK LIST:");
output.println(lib);
// The following tests the findTitles method, i.e. test
// the findTitles method by passing “Acer Dumpling” and
// then “The Bluff”:
// Write only the "Acer Dumpling" books to the output file
output.println("\nPRINT ALL ACER DUMPLINGS:");
for (Book b: lib.findTitles("Acer Dumpling")) {
output.println(b);
}
// Write only the "The Bluff" books to the output file
output.println("\nPRINT ALL THE BLUFFS:");
for (Book b: lib.findTitles("The Bluff")) {
output.println(b);
}
// Close all open files and end main.
input.close();
output.close();
}
// Header for method that separates author names and
// returns an ArrayList<String> containing the author names
public static ArrayList < String > getAuthors(String theAuthors) {
String[] temp = theAuthors.split("\\*");
ArrayList < String > result = new ArrayList < String > (Arrays.asList(temp));
return result;
}
}
After running this program, the output file only loads like this:
PRINT WITH NEW BOOK UNSORTED:
(the list of books' title and authors)
PRINT ALL SORTED BOOK LIST:
(the list of books' title and authors)
PRINT ALL ACER DUMPLINGS:
(the list of title with acer dumpling)
PRINT ALL THE BLUFFS:
(the list of title with the bluff)
The first two parts "PRINT INITIAL BOOK LIST" and "PRINT SORTED BOOK LIST" are missing but I don't know how to figure that out.
Thanks!

You have asked don't know how to figure that out.
My answer is mentioned below:
Import your project in the eclipse.
Put the debug point in your code at multiple points.
Use the bug icon in eclipse to debug the class file.
Once it hits the debug pointer you have set, use F6 to debug it line by line or you can
use F5 to jump into the method.
You can also refer the link mentioned below:
https://www.eclipse.org/community/eclipse_newsletter/2017/june/article1.php

Related

Reading text from file and comparing it to seriers of characters

can I get recommendation or like an advice for what should be used or be known to complete this task (in the most rudimentary way I guess). if someone would be willing to write a code that would be fantastic but vague answers on the neccesary knowledge or technique will suffice.
I would like a program where at the start you input characters either seperataed by pressing enter or a string that could be like chopped up into separate items of an array (I guess) - characters separated by a comma - and that would be then compared to a txt file that contains series of entries and only those that contain some of (meaning shorter) or all of the characters that have been provided at the start would be printed, perhaps even the print would be separated by a length of the entry (word).
Any ideas on how to do this? Also, can the results be printed somewhere else than the command line, like another txt file? Need to do this in java. Thanks.
Take a look at following example:
public class SimpleExample {
public static void main(String[] args) throws ClassNotFoundException {
Scanner inputNumbers = new Scanner(System.in);
List<Integer> listOfNumbersToStore = new ArrayList<>();
List<Integer> listOfNumbersToCheck = new ArrayList<>();
int number;
String answer;
boolean flag = true;
// do code within a loop while flag is true
do {
// print message to screen
System.out.print("Would you like to put new number to your file list (Y/N): ");
// get answer (Y/N) to continue
answer = inputNumbers.next();
// if answer is Y or y
if ("Y".equalsIgnoreCase(answer)) {
// print message
System.out.print("Put your number: ");
// get input integer and assign it to number
number = inputNumbers.nextInt();
// add that number to a list of numbers to store to file
listOfNumbersToStore.add(number);
} else if ("N".equalsIgnoreCase(answer)) {
flag = false;
}
} while (flag);
writeToFile(listOfNumbersToStore);
System.out.println("---------- Check numbers ----------");
flag = true; // set it again to true
//do code within a loop while flag is true
do {
System.out.print("Would you like to put new number to your check list (Y/N) : ");
answer = inputNumbers.next();
if ("Y".equalsIgnoreCase(answer)) {
System.out.print("Put your number: ");
number = inputNumbers.nextInt();
listOfNumbersToCheck.add(number);
} else if ("N".equalsIgnoreCase(answer)) {
flag = false;
}
} while (flag);
// get a list from a file
List<Integer> readFromFile = readFromFile();
// check if there are any common elements within compared lists
boolean areThereAnyCommonElements = !Collections.disjoint(
listOfNumbersToCheck, readFromFile);
//create a new treeset used for containing unique elements and ordering it naturally, from 0 to n
Set<Integer> set = new TreeSet<>(listOfNumbersToCheck);
set.retainAll(readFromFile);
// print these messages
System.out.println("Are there any common integers between a list from a file and checking list? " + areThereAnyCommonElements);
System.out.println("Those integers are: " + set.toString());
}
/**
* List implements Seriazable interface, therefore store it to a file
* serialized
*
* #param numberOfIntegers
*/
public static void writeToFile(List<Integer> numberOfIntegers) {
try {
// create a file output stream to write to the file with the specified name.
FileOutputStream fileOutputStream = new FileOutputStream("tekstDataOutputStream");
// writes the serialization stream header to the underlying file stream;
ObjectOutputStream dataOutputStream = new ObjectOutputStream(new BufferedOutputStream(fileOutputStream));
// write a list to object output stream
dataOutputStream.writeObject(numberOfIntegers);
//close them
dataOutputStream.close();
fileOutputStream.close();
} catch (IOException ioE) {
System.err.println("JVM reported an error! Take a look: " + ioE);
}
}
public static List<Integer> readFromFile() throws ClassNotFoundException {
//create an empty list of integers
List<Integer> result = new ArrayList<>();
try {
//opening a connection to an actual file
FileInputStream fis = new FileInputStream("tekstDataOutputStream");
//used for reading from a specified input stream
ObjectInputStream reader = new ObjectInputStream(fis);
//get that list
result = (List<Integer>) reader.readObject();
//close streams
reader.close();
fis.close();
} catch (IOException ioE) {
System.err.println("JVM reported an error! Take a look: " + ioE);
}
return result;
}
}

How to read inputs from a text file and put those inputs into an ArrayList in Java?

so I want to read in a text file with a bunch of inputs containing strings like this:
abc456
mnjk452
aaliee23345
poitt78
I want to put each of these inputs into an array list and pass that arraylist through one of my methods. How would I go about doing so? Currently in my code, I'm trying to see if i can simply print out what's in my arraylist. Here is what i have in my main:
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("Give me a file!");
}
String fname = args[0];
ArrayList<String> coordinates = new ArrayList<String>();
Scanner grid = new Scanner(fname);
while(grid.hasNext()) {
coordinates.add(grid.nextLine());
}
for(String coordinate : coordinates) {
System.out.println(coordinate);
}
}
How about this:
Path path = Paths.get(args[0]);
List<String> coordinates = Files.readAllLines(path);
System.out.print(coordinates); // [abc456, mnjk452, aaliee23345, poitt78]
Same can be accomplished with the Scanner:
Path path = Paths.get(args[0]);
List<String> result = new ArrayList<>();
Scanner sc = new Scanner(path);
while (sc.hasNextLine()) {
String line = sc.nextLine();
result.add(line);
}
System.out.print(result); // [abc456, mnjk452, aaliee23345, poitt78]
Do not forget to pass your arguments when you run your application (either in your IDE or command line)!
When reading from a file you need to create a File object that you give to the Scanner object. Also you should control your while loop based on grid.hasNextLine() since you are grabbing line by line. Lastly when running the program from terminal you should be doing the following
java "name of your class with main" "file name"
Which will pass that file in as a parameter to args[0]
try
{
Scanner grid = new Scanner(new File(fname));
while(grid.hasNextLine())
{
coordinates.add(grid.nextLine());
}
}catch(FileNotFoundException e)
{
System.err.println("File " + fname + " does not exist/could not be found");
e.printStackTrace();
}

How do I update a file using an ArrayList, Java

I am writing a method that will take in some command line arguments, validate them and if valid will edit an airport's code. The airport name and it's code are stored in a CSV file. An example is "Belfast,BHD". The command line arguments are entered as follows, java editAirport EA BEL Belfast, "EA" is the 2letter code that makes the project know that I want to Edit the code for an Airport, "BEL" is the new code, and Belfast is the name of the Airport.
When I have checked through the cla's and validated them I read through the file and store them in an ArrayList as, "Belfast,BEL". Then I want to update the text file by removing the lines from the text file and dumping in the arraylist, but I cannot figure out how to do it. Can someone show me a way using simple code (no advanced java stuff) how this is possible.
Here is my program
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class editAirport
{
public static void main(String [] args)throws IOException
{
String pattern = "[A-Z]{3}";
String line, line1, line2;
String[] parts;
String[] parts1;
boolean found1 = false, found2 = false;
File file = new File("Airports.txt"); // I created the file using the examples in the outline
Scanner in = new Scanner(file);
Scanner in1 = new Scanner(file);
Scanner in2 = new Scanner(file);
String x = args[0], y = args[1], z = args[2];
//-------------- Validation -------------------------------
if(args.length != 3) // if user enters more or less than 3 CLA's didplay message
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(file.exists())) // if "Airports.txt" doesn't exist end program
JOptionPane.showMessageDialog(null, "Airports.txt does not exist");
else // if everything is hunky dory
{
if(!(x.equals("EA"))) //if user doesn't enter EA an message will be displayed
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(y.matches(pattern))) // If the code doesn't match the pattern a message will be dislayed
JOptionPane.showMessageDialog(null, "Airport Code is invalid");
while(in.hasNext())
{
line = in.nextLine();
parts = line.split(",");
if(y.equalsIgnoreCase(parts[1]))
found1 = true; //checking if Airport code already is in use
if(z.equalsIgnoreCase(parts[0]))
found2 = true; // checking if Airport name is in the file
}
if(found1)
JOptionPane.showMessageDialog(null, "Airport Code already exists, Enter a different one.");
else if(found2 = false)
JOptionPane.showMessageDialog(null, "Airport Name not found, Enter it again.");
else
/*
Creating the ArrayList to store the name,code.
1st while adds the names and coses to arraylist,
checks if the name of the airport that is being edited is in the line,
then it adds the new code onto the name.
sorting the arraylist.
2nd for/while is printing the arraylist into the file
*/
ArrayList<String> airport = new ArrayList<String>();
while(in1.hasNext()) // 1st while
{
line1 = in1.nextLine();
if(line1.contains(z))
{
parts1 = line1.split(",");
parts1[1] = y;
airport.add(parts1[0] + "," + parts1[1]);
}
else
airport.add(line1);
}
Collections.sort(airport); // sorts arraylist
FileWriter aFileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(aFileWriter);
for(int i = 0; i < airport.size();)
{
while(in2.hasNext()) // 2nd while
{
line2 = in2.nextLine();
line2 = airport.get(i);
output.println(line2);
i++;
}
}
output.close();
aFileWriter.close();
}
}
}
}
The Airports.txt file is this
Aberdeen,ABZ
Belfast City,BHD
Dublin,DUB
New York,JFK
Shannon,SNN
Venice,VCE
I think your problem may lie in the two lines:
line2 = in2.nextLine();
line2 = airport.get(i);
this will overwrite the 'line2' in memory, but not in the file.

How to read certain parts of a file and store it into an array in java

so I currently have a String array called Hotel. In this array, the elements contains names of people who are staying in a hotel. (I wrote a while loop and the user just enters a room number and a name. The room number corresponds to the array index and the name contains the element for that particular index. E.g. 3 Jim, in the array, the 4th index would be contained with the element 'Jim'. I cannot use a arraylist, only array.. part of the specificication i was handed).
This is part of the whole program. This is the method I wrote to save the array data into a file:
private static void savingToFile(String[] hotelRef) {
System.out.println("Creating a text file called Hotel Data");
File fileObject = new File("C://Hotel_Data.txt");
if (!fileObject.exists()) {
try {
fileObject.createNewFile();
System.out.println("File has been created in the C directory");
} catch (IOException e) {
System.out.println("Something went wrong in the process " + e);
}
}
try {
FileWriter fs = new FileWriter(fileObject);
BufferedWriter writer = new BufferedWriter(fs);
for (int i = 0; i < hotelRef.length; i++) {
String hoteldata = i + " " + hotelRef[i];
writer.write(hoteldata);
writer.newLine();
}
writer.close();
} catch (IOException e) {
System.out.println("Something went wrong " + e);
}
}
I've runned the program and it works fine. Outputs a file in which it contains the room number and the name of the person currently occupied in that room.
Now I need to make another method in which I can load the data from the file into the array but I don't know how get the individual parts in the file. E.g. I dont know how to only get the name from the data without getting the room number..
Just read the file and use String.split method to get the room number and name. Something like this:
String[] hotelRef = new String[MAX_NO_OF_ROOMS];
FileInputStream in = new FileInputStream("Hotel_Data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String hotelLine;
while((hotelLine = br.readLine())!= null)
{
//split the line contents
String hotelLineItems[] = hotelLine.split("\\s");
Integer roomNo = Integer.valueOf(hotelLineItems[0]);
String name = hotelLineItems[1];
hotelRef[roomNo] = name;
}

Cannot print to text file from within while-loop

So I'm at a point in my program where I want to read from a csv file (which has two columns), do some light calculation on the first column (after I check whether or not it has any content), then print the new number (which I calculated from column 1 in the first file) and the contents of the second column from the original file to a new text file.
Without a while loop I have no trouble running calculations on the numbers from the original text file, then printing them to the new file. However ANY printing from inside the while loop is giving me an error. In fact, anything other than reading the file and parsing it into an array of strings is giving me an error from inside the while loop.
These are the top two lines of my stackTrace with the code I currently have posted below:
"Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at finalProyect.User.makeMealPlan(User.java:476)"
Line 476 being the line in my while loop: "if (array2[0].isEmpty())"
After hours of searching and tinkering I thought it was time to ask for help. Thanks in advance for any help you can provide.
public void makeMealPlan() {
String fileIn = "mealPlan1.csv";
Scanner inputStream = null;
String fileOut = userName + ".txt";
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new File(fileIn));//opens and reads pre-configured meal plan
outputStream = new PrintWriter(fileOut);//creates output file for meal plan
} catch(FileNotFoundException e3) {
fileNotFound();
e3.printStackTrace();
}
outputStream.println(toString());
outputStream.println();
String line0 = inputStream.nextLine();
String[] array0 = line0.split(","); //Splits line into an array of strings
int baseCalories = Integer.parseInt(array0[0]); //converts first item in array to integer
double caloricMultiplier = (caloricNeeds / baseCalories); //calculates the caloricMultiplier of the user
String line1 = inputStream.nextLine();//reads the next line
String[] array1 = line1.split(",");//splits the next line into array of strings
outputStream.printf("%12s %24s", array1[0], array1[1]); //prints the read line as column headers into text file
while(inputStream.hasNextLine()) {
String line = inputStream.nextLine(); //reads next line
String[] array2 = line.split(",");
if(array2[0].isEmpty()) {
outputStream.printf("%12s %24s", array2[0], array2[1]);
} else {
double quantity = Double.parseDouble(array2[0]);
quantity = (quantity * caloricMultiplier);
outputStream.printf("%12s %24s", quantity, array2[1]);
}
}
outputStream.close();
System.out.println(toString());
}
Okay, so there were a few things wrong. However with #NonSecwitter's suggestion I was able to pin it down. So first thing (again as NonSecwitter mentioned) I had empty fields in my .csv which was throwing the ArrayIndexOutOfBounds" error. So what I did was I filled every empty field in my .csv with the string "empty". Once I did that I was able to at least print the next line.
After that, I ran into another error which was that this line:
double quantity = Double.parseDouble(array2[0]);
could not be separated from the the preceding read/split statements by being inside of an if-loop. So I ended up rewriting the guts of the entire while-loop and needed to throw an exception like so:
while (inputStream.hasNextLine())
{
String[] array2 = null;
try
{
String line = inputStream.nextLine(); //reads next line
array2 = line.split(",");
double quantity = Double.parseDouble(array2[0]);
if (!isStringNumeric(array2[0]))
throw new NumberFormatException();
quantity = Math.ceil(quantity * caloricMultiplier);
outputStream.printf("%12.1f %15s\n", quantity, array2[1]);
}
catch(NumberFormatException e1)
{
if (array2[1].equals("empty"))
outputStream.printf("%12s %15s\n", " ", " ");
else
outputStream.printf("%12s %15s\n", " ", array2[1]);
}
}
While my program is now currently working just fine, I'd still really appreciate an explanation as to why I ended up having to throw an exception to get the code to work. Are there certain restrictions with using PrintWriter inside of a while-loop? Also, I very much appreciate everybody's feedback. I think with all the comments/suggestions combined I was able to determine where my problems were (just not WHY they were problems).
Thanks!!!
It would help if you provided sample CSV data and an example of the related output you expect in <userName>.txt.
Short of this I can only help insofar as saying I do not get an exception with your code.
Here is what I got with a quick Java project in Eclipse using project and class-file names gleaned from your exception output (finalProyect and User.java respectively), pasting your code into the class file (User.java), and massaging it a bit for a sanity check...
package finalProyect;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class User {
public void makeMealPlan()
{
String fileIn = "C:\\Temp\\mealPlan1.csv";//"mealPlan1.csv"; // FORNOW: adjusted to debug
Scanner inputStream = null;
String userName = "J0e3gan"; // FORNOW: added to debug
String fileOut = "C:\\Temp\\" + userName + ".txt"; // FORNOW: adjusted to debug
PrintWriter outputStream = null;
try
{
inputStream = new Scanner(new File(fileIn));//opens and reads pre-configured meal plan
outputStream = new PrintWriter(fileOut);//creates output file for meal plan
}
catch(FileNotFoundException e3)
{
//fileNotFound(); // FORNOW: commented out to debug
e3.printStackTrace();
}
outputStream.println(toString());
outputStream.println();
String line0 = inputStream.nextLine();
String[] array0 = line0.split(","); //Splits line into an array of strings
int baseCalories = Integer.parseInt(array0[0]); //converts first item in array to integer
int caloricNeeds = 2000; // added to debug
double caloricMultiplier = (caloricNeeds / baseCalories); //calculates the caloricMultiplier of the user
String line1 = inputStream.nextLine();//reads the next line
String[] array1 = line1.split(",");//splits the next line into array of strings
outputStream.printf("%12s %24s", array1[0], array1[1]); //prints the read line as column headers into text file
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine(); //reads next line
String[] array2 = line.split(",");
if (array2[0].isEmpty())
outputStream.printf("%12s %24s", array2[0], array2[1]);
else
{
double quantity = Double.parseDouble(array2[0]);
quantity = (quantity * caloricMultiplier);
outputStream.printf("%12s %24s", quantity, array2[1]);
}
}
outputStream.close();
System.out.println(toString());
}
public static void main(String[] args) {
// FORNOW: to debug
User u = new User();
u.makeMealPlan();
}
}
...and an example of what it output to J0e3gan.txt...
finalProyect.User#68a6a21a
3000 40 2500.0 50 4000.0 25
...with the following (complete-WAG) data in mealPlan1.csv:
2000,20
3000,40
2500,50
4000,25
Comment out the offending code and try to println() array2[0] and see if it gives you anything.
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine(); //reads next line
String[] array2 = line.split(",");
System.out.println(array2[0]);
//if (array2[0].isEmpty())
// outputStream.printf("%12s %24s", array2[0], array2[1]);
//
//else
//{
//
// double quantity = Double.parseDouble(array2[0]);
// quantity = (quantity * caloricMultiplier);
// outputStream.printf("%12s %24s", quantity, array2[1]);
//}
}
or, try to print the length. If the array were empty for some reason array2[0] would be out of bounds
System.out.println(array2.length);
I would also print line to see what it's picking up
System.out.println(line);

Categories

Resources