Read from 1 file to produce 2 files - java

I've been trying to do this problem for my schoolwork and for the life of me I cannot figure it out.
The problem is: Write a program that reads in "worked_example_1/babynames.txt" and produces two files, boynames.txt and girlnames.txt, separating the data for the boys and girls.
This is the code from Worked Example 11 from wiley.com/go/javaexamples for this problem:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class BabyNames
{
public static final double LIMIT = 50;
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(new File("babynames.txt"));
RecordReader boys = new RecordReader(LIMIT);
RecordReader girls = new RecordReader(LIMIT);
while (boys.hasMore() || girls.hasMore())
{
int rank = in.nextInt();
System.out.print(rank + " ");
boys.process(in);
girls.process(in);
System.out.println();
}
in.close();
}
}
And this:
import java.util.Scanner;
public class RecordReader
{
private double total;
private double limit;
public RecordReader(double aLimit)
{
total = 0;
limit = aLimit;
}
public void process(Scanner in)
{
String name = in.next();
int count = in.nextInt();
double percent = in.nextDouble();
if (total < limit)
{
System.out.print(name + " ");
}
total = total + percent;
}
public boolean hasMore()
{
return total < limit;
}
}
I created the babynames.txt and put in the same src folder as the .java file, it comes up with file not found, if I give the direct path to the file with
Scanner in = new Scanner(new File("C:/Users/me/SkyDrive/Schoolwork/CIS150AB/Chapter 11.1/src/babynames.txt"));
it finds the file but gives me this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at BabyNames.main(BabyNames.java:20)
To me it looks like this error is because of Line 20 where int rank = in.nextInt(); and its looking for a string when its looking for an int, but this is directly from Wiley website so I am not sure.
Any help with this would be appreciated, apparently I am not meant for online classes for Java. Next class I am taking in school once there is one that works around my schedule.

If this is the format of your babynames.txt, this is what'll happen (I think, didn't try it).
The scanner "in" reads the first int into "rank" (OK)
Enter into boys.process()
"in" reads the first name (Jacob)
"in" tries to read the first int (1), but finds 1.0013, which is not an int
This scenario doesn't match your error (you'd get a stacktrace from RecordReader rather than from BabyNames) but maybe the line of thinking will work for you.
Try it with a debugger. If you can't, use in.next() rather than in.nextInt() or in.nextDouble(). You can than print the value and see why it's not what you think it is.
Your question actually raises two questions. The answer to the hidden one may be:
try (InputStream inputStream = BabyNames.class.getResourceAsStream("/babynames.txt");
Scanner in = new Scanner(inputStream))
{
// do stuff with in
}

Related

Number of elements in Periodic Table shows up as 0 and not 118

I need to output the number of elements from a dat file. The number of elements needs to be 118 but I get 0.
import java.io.*;
import java.util.Scanner;
public class PeriodicTable
{
public static void main(String[] args) throws IOException
{
final int MAX_ELEMENTS = 128;
int[] atomicNumber = new int[MAX_ELEMENTS];
File file = new File("periodictable.dat");
Scanner inputFile = new Scanner(file);
int currentElements = 0;
while(inputFile.hasNext())
{
atomicNumber[currentElements] = inputFile.nextInt();
String symbol = inputFile.next();
float mass = inputFile.nextFloat();
String name = inputFile.next();
currentElements++;
}
inputFile.close();
System.out.println("Periodic Table\n");
System.out.println(currentElements + " elements");
}
}
When I run the sample class it seems to work correctly for me, so I assume there is and issue with the periodictable.dat file.
With a test periodictable.dat file filled with the following:
110 T 200.00 Test
300 A 100.18 Again
I get the following output:
Periodic Table
2 elements
If there was a formatting error in the file you would receive a mismatch exception. So I would
Check your file is not empty as this would cause the while condition to be false.
I would also add what your current file looks like in your question :)

Reading file in java on Mac

I am doing a tutorial on java and the video I am at now deals with FileReading, but it is for windows and I am on a mac. Please help
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 = "/Users/--MyUsername--/Desktop/test.rtf";
File textFile = new File(fileName);
Scanner in = new Scanner(textFile);
int value = in.nextInt();
System.out.println("Read value: " + value);
in.nextLine();
int count = 2;
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println(count + ": " + line);
count++;
}
in.close();
}
}
and this is the error that I am getting
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at L37ReadingTextFiles.App.main(App.java:17)
Please help
You are trying to read integers from the file, but the content is not integer, please use String value = in.next(); instead of int value = in.nextInt();
The problem is probably with the .rtf file. There might be a way to get that type of file to work as expected in java, but for a beginner, I would recommend making it a .txt file.

Receiving StringIndexOutOfBoundsException but unable to locate the source

My task:
Use scanner method to extract a string, a float, and an int from a line of data.
The data format is:
Random String, 240.5 51603
Another String, 41.6 59087
etc.
My source snippet:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class readTest {
public static void main(String args[]) throws FileNotFoundException
{
System.out.println ("Enter file name");
Scanner scanInput = new Scanner(System.in); //Scanner for reading keyboard input for file name
String fileName = scanInput.nextLine(); //Defines file name as a string from keyboard
File inputTxt = new File(fileName); //Declares the file based on the entered string
Scanner in = new Scanner(inputTxt);
do {
int a; //variable to count how many characters in name
String baseStringA = in.nextLine(); //read whole line as string
a = baseStringA.indexOf(","); //defines a as the posistion of the comma
String reduceStringA = baseStringA.substring(0, a); //reduces string to everything before comma
Scanner scanA = new Scanner(baseStringA).useDelimiter("[^.0-9]+"); //removes letters and comma from string
Float numberA = scanA.nextFloat();
int integerA = scanA.nextInt();
System.out.print (reduceStringA + numberA + integerA);
} while (in.hasNextLine());
}
}
So I finally managed to spit out this code after researching a few different topics (I am pretty new to any type of coding) and I was so excited that I managed to get the output I wanted. But after attempting to implement a loop to make the process repeat for all of the available lines, I frequently hit a wall with the error java.lang.StringIndexOutOfBoundsException after the program prints the output of the first line.
The full error:
String index out of range: -1
at java.lang.String.substring(Unknown Source)
at readTest.main(readTest.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
I tried to research a little, and I'm convinced it comes from my line
String reduceStringA = baseStringA.substring(0, a);
This seemed more obvious as I tried to read the actual info given by the error, but when I try to trace where the program is having problems I come up empty.
Is anybody able to spot my rookie mistake? Or am I simply going about this process entirely wrong?
The input txt:
Stringy String, 77.2 36229
More Much String, 89.4 24812
Jolly Good String, 182.3 104570
is an example of me getting the error
While the input
Random String, 240.5 51603
Another String, 41.6 59087
String String, 182.6 104570
works as intended
Which is really strange to me.
int a; //variable to count how many characters in farm name
String baseStringA = in.nextLine(); //read whole line as string
a = baseStringA.indexOf(","); //defines a as the posistion of the comma
String reduceStringA = baseStringA.substring(0, a);
If there is no comma in the baseStringA baseStringA.indexOf() will return -1. Thus then you will try to get sub string (0,-1) and thus the error.
Finally the error comes from here baseStringA.substring(0, a); because one of begin index 0 is larger than the end index a (which is -1) - more here

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.

File I/O Basics

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

Categories

Resources