File I/O Basics - java

I'm working on a school programming lab and I've gotten stuck. The book is not too helpful in teaching how to format I/O properly, or at least I'm not understanding it properly. I need a bit of help getting on with the next steps, but here's the full requirements of the program I'm supposed to be making:
A hotel salesperson enters sales in a text file. Each line contains
the following, separated by semicolons: The name of the client, the
service sold (such as Dinner, Conference, Lodging, and so on), the
amount of the sale, and the date of that event. Write a program that
reads such a file and displays the total amount for each service
category. Display an error if the file does not exist or the format is
incorrect. In addition to the program specifications listed, your
program should both print the results as well assend the results to a
separate output file.
Example of input.txt:
Elmer Fudd;Lodging;92.00;11-01-2014
Elmer Fudd;Conference;250.00;11-02-2014
Daffy Duck;Dinner;19.89;11-02-2014
Daffy Duck;Conference;275.00;11-02-2014
Mickey Mouse;Dinner;22.50;11-02-2014
Mickey Mouse;Conference;275.00;11-02-2014
I'm currently stuck on figuring out how to get the file properly loaded and formatted, which I think I did right, but then my professor suggested breaking each into it's own line, but nowhere in my book does it clearly tell how to do that. Just to be clear, I'm not looking for a coding miracle, I just would like someone to help guide me in the right direction as to what I should do next. Possibly a better way to handle this situation in a nicely detailed guide? Nothing fancy though. Thank you in advance, and here's my current code.
import java.util.*;
import java.io.*;
public class Sales
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter("output.txt");
double dinnerTotal = 0;
double conferenceTotal = 0;
double lodgingTotal = 0;
Scanner lineScanner = new Scanner(inputFile);
lineScanner.useDelimiter(";");
while (lineScanner.hasNext())
{
String line = in.nextLine(); //Here's where I'm really stuck
System.out.print(line); //Not to say I'm not stumped all over.
}
in.close();
out.close();
lineScanner.close();
}
}
From what Jason said, I'm at this now:
import java.util.*;
import java.io.*;
public class Sales
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("input.txt");
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter("output.txt");
double dinnerTotal = 0;
double conferenceTotal = 0;
double lodgingTotal = 0;
while (in.hasNext())
{
String line = in.nextLine();
String[] parts = line.split(";");
if(parts[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(parts[2]);
}
}
in.close();
out.close();
}
}

Stick to one scanner.
Read each line in total, rather than breaking on the ';'.
Then use String.split() to break the line of text apart at the ';' separator.
Then check the second part (zero based index) to retrieve the service category and add the value in the third part to the relevant total.
String line = in.nextLine();
String[] parts = line.split(";");
if(parts[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(parts[2]);
} else if(parts[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(parts[2]);
}

Related

Reading multiple data types from a CSV file in Java

So I want to create a constructor that reads in a line of a file from a csv and save the first token into a variable and the remaining tokens into an array. This constructor will be used in a gradebook application but being new to txt/file manipulation I'm having a hard time.
A line will look like:
Billy Bob,68,79,95,83
I want to separate the tokens into these:
name = Billy Bob
grades[] = "68,79,95,83"
here is the code I have so far:
import java.io.*;
public class gradeBook {
public static void main(String[] args){
System.out.println("Java Grade Book version 1.0");
int lineCounter = 0;
String array[];
try{
File data = new File("/file/path/that/works");
InputStream f = new FileInputStream(data);
BufferedReader br = new BufferedReader(new InputStreamReader(f));
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line); // just here to check that the code is working thus far
//insert code here
//name should equal first token (which is two names like Billy Bob)
//grades[] should contain the other double type tokens (e.g. 56,87,89,90)
}
br.close();
}
catch(Exception e){
System.err.println("Error: File Couldn't Be Read");
}
}
}
And I want to loop through the file to get as many students as are on the file stored so I can manipulate the grades for averages among other things. This is a personal project to help improve my developing skills so any help, useful tutorial links, and tips will be greatly appreciated. But please don't suggest simplistic examples like the many tutorials I have already read that only use one data type.
Thanks for any help!
Split the line into an array;
String[] input = line.split(",");
String variable = input[0];
int[] grades= new int[input.lenght - 2];
for(int i = 1; i < input.length; i++)
{
grades[i] = input[i];// you might have to do Integer.pareseInt(input[i]);
}
I did not write this in an IDE, but the logic should be correct.
You are going to run into a new problem. You grade book will only contain the last entry. Try using a 2D array for grades and 1D array for names; I personally would not use arrays. I would use arraylist.
So I haven't tested computing my tokens with methods or anything else yet but I have tokenized the line to sum (ha ha oops, meant some) degree with this bit of code:
String[] tokens = line.split(",");
String name = tokens[0];
String grade1 = tokens[1];
String grade2 = tokens[2];
String grade3 = tokens[3];
String grade4 = tokens[4];

Java scanner not starting from beginning of file

First of all this is not a duplicate of other posts, because in my problem the scanner class does not recognize the beginning of the .txt file not the end, instead it starts approximately 1/2 way through the file.
Here is my code:
package Program;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws FileNotFoundException {
String filename = "C:\\Users\\vroy\\Programming\\Text documents\\P&P.txt";
File textFile = new File(filename);
Scanner reader = new Scanner(textFile);
// int value = reader.nextInt();
// System.out.println(value);
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
}
reader.close();
}
}
Here is the .txt document that my program is reading:
http://www.goodreads.com/ebooks/download/1885.Pride_and_Prejudice?doc=2
My program starts printing out lines of text starting at: "with the ill-judged officiousness..."
It should start much further up the document.
Is this a problem with the scanner class?
Is this a problem with the scanner class?
Nope.
I just tested your code. The answer is pretty funny actually - I assume you are running this code in an IDE such as Eclipse. System.out.println() prints to the "Console". The console has a maximum number of lines it shows, and as your file is very long, it doesn't show the start.
It IS looping through all the lines. To prove this, make it increment a digit whenever it prints a line such as:
int counter = 0;
while (reader.hasNextLine()) {
String line = reader.nextLine();
System.out.println(line);
counter++;
}
You will see that counter is exactly the number of lines in the document.

Using scanner with a prompt and user input

I tried to do counting lines, words, character from user "inputted" file.
After this show counting and keep asking again.
If file doesn't exist print all data which have been counted during running.
Code:
public class KeepAskingApp {
private static int lines;
private static int words;
private static int chars;
public static void main(String[] args) {
boolean done = false;
//counters
int charsCount = 0, wordsCount = 0, linesCount = 0;
Scanner in = null;
Scanner scanner = null;
while (!done) {
try {
in = new Scanner(System.in);
System.out.print("Enter a (next) file name: ");
String input = in.nextLine();
scanner = new Scanner(new File(input));
while(scanner.hasNextLine()) {
lines += linesCount++;
Scanner lineScanner = new Scanner(scanner.nextLine());
lineScanner.useDelimiter(" ");
while(lineScanner.hasNext()) {
words += wordsCount++;
chars += charsCount += lineScanner.next().length();
}
System.out.printf("# of chars: %d\n# of words: %d\n# of lines: ",
charsCount, wordsCount, charsCount);
lineScanner.close();
}
scanner.close();
in.close();
} catch (FileNotFoundException e) {
System.out.printf("All lines: %d\nAll words: %d\nAll chars: %d\n",
lines, words, chars);
System.out.println("The end");
done = true;
}
}
}
}
But I can't understand why it always show output with no parameters:
All lines: 0
All words: 0
All chars: 0
The end
Why it omits all internal part.
It may be coz I'm using few scanners, but all look ok.
Any suggestions?
UPDATE:
Thanks all who give some hint. I rethinking all constructed and rewrite code with newly info.
To awoid tricky scanner input line, I used JFileChooser:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class KeepAskingApp {
private static int lines;
private static int words;
private static int chars;
public static void main(String[] args) {
boolean done = false;
// counters
int charsCount = 0, wordsCount = 0, linesCount = 0;
Scanner in = null;
Scanner lineScanner = null;
File selectedFile = null;
while (!done) {
try {
try {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
while (in.hasNextLine()) {
linesCount++;
lineScanner = new Scanner(in.nextLine());
lineScanner.useDelimiter(" ");
while (lineScanner.hasNext()) {
wordsCount++;
charsCount += lineScanner.next().length();
}
}
System.out.printf(
"# of chars: %d\n# of words: %d\n# of lines: %d\n",
charsCount, wordsCount, linesCount);
lineScanner.close();
lines += linesCount;
words += wordsCount;
chars += charsCount;
in.close();
} finally {
System.out.printf(
"\nAll lines: %d\nAll words: %d\nAll chars: %d\n",
lines, words, chars);
System.out.println("The end");
done = true;
}
} catch (FileNotFoundException e) {
System.out.println("Error! File not found.");
}
}
}
}
Couple of issues (actually there are many issues with your code, but I will address the ones directly related to the output you have posted):
First of all, the stuff in the catch block only happens if you get a FileNotFoundException; that's there to handle and recover from errors. I suspect you meant to put a finally block there, or you meant to do that after the catch. I suggest reading this tutorial on catching and handling exceptions, which straightforwardly describes try, catch, and finally.
Once you read that tutorial, come back to your code; you may find that you have a little bit of reorganizing to do.
Second, with the above in mind, it's obvious by the output you are seeing that you are executing the code in that catch block, which means you are getting a FileNotFoundException. This would be caused by one of two (possibly obvious) things:
The file you entered, well, wasn't found. It may not exist or it may not be where you expect. Check to make sure you are entering the correct filename and that the file actually exists.
The input string is not what you expect. Perhaps you read a blank line from previous input, etc.
Addressing reason 2: If there is already a newline on the input buffer for whatever reason, you will read a blank line with Scanner. You might want to print the value of input just before opening the file to make sure it's what you expect.
If you're seeing blank lines, just skip them. So, instead of this:
String input = in.nextLine();
scanner = new Scanner(new File(input));
Something like this instead would be immune to blank lines:
String input;
do {
input = in.nextLine().trim(); // remove stray leading/trailing whitespace
} while (input.isEmpty()); // keep asking for input if a blank line is read
scanner = new Scanner(new File(input));
And, finally, I think you can work out the reason that you're seeing 0's in your output. When you attempt to open the file with new Scanner(new File(input)); and it fails because it can't find the file, it throws an exception and the program immediately jumps to the code in your catch block. That means lines, words, and chars still have their initial value of zero (all code that modifies them was skipped).
Hope that helps.
Your println()s are in a catch block
} catch (FileNotFoundException e) {
System.out.printf("All lines: %d\nAll words: %d\nAll chars: %d\n",
lines, words, chars);
System.out.println("The end");
done = true;
}
That means you caught a FileNotFoundException. I think you can figure out from here.

Java Read from file to Array runtime error

import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();

print only array items that are greater than a certain int

I wrote this simple script that reads a text file and then adds the data to an array however i only want to print the first and last name of the students that have over 90 credits
Student[] student = new Student[50];
Scanner userin, filein;
String filename;
int numStudents;
// Get the filename from the user, with exception handling to deal with incorrect file names
userin = new Scanner(System.in);
filename = null;
filein = null;
filename = Students.txt;
try {
filein = new Scanner(new FileReader(filename)); // try to open the file
} catch (FileNotFoundException e) { // failed to open the file
System.out.println("Invalid file - try again");
filename = null;
}
numStudents = 0;
while (filein.hasNext()){
String lastName = filein.next();
String firstName = filein.next();
double gpa = filein.next();
int Credits = filein.next();
student[numStudents++] = new Student(lastName,firstName,gpa,Credits);
}
int i=0;
do
{
System.out.println(student[i].toString());
i++;
}
while ((student[i] != null)&&(i <= student.length));
"script"?
This is some ugly code. Formatting and structure matter. I'd recommend paying more attention to it in the future. It'll make your maintenance life easier as your programs (aka "scripts") become more complex.
Learn the Sun Java coding standards. You aren't following them now.
Everything in Java has to be a part of a class. I'll assume that you know that. This must be a snippet you cut out of your class.
Your code is too chaotic to worry about making it nice. This'll work:
if (student[i].getCredits() >= 90)
System.out.println(student[i].toString());

Categories

Resources