I have a program with the purpose of analyzing a text file that the user selects via typing in the full path of the text file when prompted.
I have managed to get the scanner into multiple classes however it will not work for each method simultaneously. For example I have a class that will print the amount of numbers in the file and another that will print the number of words in the file. However only the first method that is run will work, the other will display 0 of whatever the class is searching for(numbers, lines, words etc) even if the true value is not actually 0.
I'm really stuck with why this is happening, I have attached the main class with two other classes to show a clear example:
Main Class:
package cw;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class TextAnalyser {
public static Scanner reader;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter a filename");
String filename = in.nextLine();
File InputFile = new File (filename);
reader = new Scanner (InputFile);
LineCounter Lineobject = new LineCounter();
WordCounter Wordobject = new WordCounter();
Lineobject.TotalLines();
Wordobject.TotalWords();
}
}
Class that counts lines:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class LineCounter {
public static void TotalLines() throws IOException {
// Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
Scanner sc = TextAnalyser.reader;
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt", true));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
out.println("The total number of lines in the file = " + linetotal);
out.flush();
out.close();
System.out.println("The total number of lines in the file = " + linetotal);
}
}
Class that Counts words:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class WordCounter {
public static Scanner sc = TextAnalyser.reader;
public static void TotalWords() throws IOException{
//Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt", true));
int wordtotal = 0;
while (sc.hasNext()){
sc.next();
wordtotal++;
}
out.println("The total number of words in the file = " + wordtotal);
out.flush();
out.close();
System.out.println("The total number of words in the file = " + wordtotal);
}
}
For some reason only one will work at a time, one will always say there are 0, if someone could explain to me why this is happening and how to solve it, it would really help, Thanks!
reader = new Scanner (InputFile); contains a reference to the Scanner object, when you use public static Scanner sc = TextAnalyser.reader; in both methods you are copying the reference of reader into sc, so all of them are the same object. Why having 2 variables referencing all the same object one of which is redefined two times with the same value?
The problem here is that the scanner reaches the end of the file and when you call it again (it is the same object) it has nothing more to read, so you should create another scanner object (maybe it is what you was attempting to do?). A better solution would be to read the file once and store the contents in some data structure.
Related
I have a basic class FileOutput that will write to a textfile HighScores. I also have a class fileReader that will print out what is written in the textfile. Is there a way to read a line of the textfile HighScores and save it as a String variable? I eventually want to be able to keep track of the top 5 HighScores in a game so I will need a way to compare the latest score to those in the top 5.
Here is my code so far:
import java.util.Scanner;
import java.io.File;
public class FileReader
{
public static void main(String args[]) throws Exception
{
// Read from an already existing text file
File inputFile = new File("./src/HighScores");
Scanner sc = new Scanner(inputFile);
while (sc.hasNext()){
String s = sc.next();
System.out.println(s);
}
}
FileOutput Class:
import java.io.PrintWriter;
import java.io.FileWriter;
import java.util.ArrayList;
public class FileOutput
{
public static void main(String args[]) throws Exception
{
FileWriter outFile = new FileWriter("./src/HighScores");
PrintWriter out = new PrintWriter(outFile);
// Write text to file
out.print("Top Five High Scores");
out.println(50);
out.println(45);
out.println(20);
out.println(10);
out.println(5);
out.close();
}
}
Yes.
I'm not sure if this is the most clever method of doing so, but you could create an ArrayList and create a collection of strings. Instead of out.print'ing you could try this:
ArrayList<String> al = new ArrayList<>();
while (sc.hasNext()){
String s = sc.next();
al.add(s);
}
That will create a list of strings which you could get the top 5 values of later by saying:
String firstPlace = al.get(0);
String secondPlace = al.get(1);
String thirdPlace = al.get(2);
String fourthPlace = al.get(3);
String fifthPlace = al.get(4);
When finished output should be:
15 Michael
16 Jessica
20 Christopher
19 Ashley
etc.
I am not that good at this and would like any input whatsoever on how to get the int and strings to print line by line. I have avoided an array approach because I always have difficulty with arrays. Can anyone tell me if I am on the right track and how to properly parse or type cast the ints so they can be printed on a line to the output file? I have been working for days on this and any help would be much appreciated! Here is what I have so far.
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class NameAgeReverse
{
public static void main (String[] args)
{
System.out.println("Programmed by J");
String InputFileName;
String OutputFileName;
Scanner keyboard = new Scanner(System.in);
System.out.print("Input file: ");
InputFileName = keyboard.nextLine();
System.out.print("Output file: ");
OutputFileName = keyboard.nextLine();
Scanner inputStream = null;
PrintWriter outputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("nameAge.txt"));
outputStream =new PrintWriter(new FileOutputStream("ageName.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File nameAge.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
int x = 0;
String text = null;
String line = null;
while(inputStream.hasNextLine())
{
text = inputStream.nextLine();
x = Integer.parseInt(text);
outputStream.println(x + "\t" + text);
}
inputStream.close();
outputStream.close();
}
}
Here are my error messages:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Michael"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at NameAgeReverse.main(NameAgeReverse.java:52)
text = inputStream.nextLine(); will read the whole line of text with both name and age. Assuming the format of every line in your input file is age name, you can do the following parse every line of text into desirable values. Note that this won't work out of the box with the rest of your code. Just a pointer:
text = inputStream.nextLine().split(" "); // split each line on space
age = Integer.parseInt(text[0]); // age is the first string
name = text[1];
This should work:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class ReadWriteTextFile {
final static Charset ENCODING = StandardCharsets.UTF_8;
public static void main(String... aArgs) throws IOException{
List<String> inlines = Files.readAllLines(Paths.get("/tmp/nameAge.txt"), ENCODING);
List<String> outlines = new ArrayList<String>();
for(String line : inlines){
String[] result = line.split("[ ]+");
outlines.add(result[1]+" "+result[0]);
}
Files.write(Paths.get("/tmp/ageName.txt"), outlines, ENCODING);
}
}
the input file has lines of text like this:
allison wesley 28011990
peter smith 05071992
and my code (to try and print this to an output file) is the following(im providing both the input and output as command-line args):
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class FormatNames{
public static void main(String[] args) throws FileNotFoundException{
Scanner in = new Scanner(args[0]);
PrintWriter out = new PrintWriter(args[1]);
while(in.hasNext()){
String str = in.next();
out.print(""+str);
}
in.close();
out.close();
}
}
Does anyone know why this doesn't work?
At the moment, the only thing it outputs to the file is the name of the input file
Thanks
You are using the Scanner constructor that takes a String as input: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.lang.String)
Try to use the constructor that takes a File like:
new Scanner(new File(arg[0]));
I'm trying to write some text to a file. I have a while loop that is supposed to just take some text and write the exact same text back to the file.
I discovered that the while loop is never entered because Scanner thinks there's no more text to read. But there is.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
String whatToWrite = "";
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
PrintWriter output = new PrintWriter(theFile);
while (readinput.hasNext()) { //why is this false initially?
String whatToRead = readinput.next();
whatToWrite = whatToRead;
output.print(whatToWrite);
}
readinput.close();
output.close();
}
}
The text file just contains random words. Dog, cat, etc.
When I run the code, text.txt becomes empty.
There was a similar question: https://stackoverflow.com/questions/8495850/scanner-hasnext-returns-false which pointed to encoding issues. I use Windows 7 and U.S. language. Can I find out how the text file is encoded somehow?
Update:
Indeed, as Ph.Voronov commented, the PrintWriter line erases the file contents! user2115021 is right, if you use PrintWriter you should not work on one file. Unfortunately, for the assignment I had to solve, I had to work with a single file. Here's what I did:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> theWords = new ArrayList<String>();
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
while (readinput.hasNext()) {
theWords.add(readinput.next());
}
readinput.close();
PrintWriter output = new PrintWriter(theFile); //we already got all of
//the file content, so it's safe to erase it now
for (int a = 0; a < theWords.size(); a++) {
output.print(theWords.get(a));
if (a != theWords.size() - 1) {
output.print(" ");
}
}
output.close();
}
}
PrintWriter output = new PrintWriter(theFile);
It erases your file.
You are trying to read the file using SCANNER and writing to another file using PRINTWRITER,but both are working on same file.PRINTWRITER clear the content of the file to write the content.Both the class need to work on different file.
I am working on a project for java and I want the comiler to differentiate between number and words, but when I try the code as is, it returns error due to string of -1. Also, how do I make the number I am reading in into * symbols in a graph? Any help would be greatly appreciated
Orville’s Acres, 114.8 43801
Hoffman’s Hills, 77.2 36229
Jiffy Quick Farm, 89.4 24812
Jolly Good Plantation, 183.2 104570
Organically Grown Inc., 45.5 14683
(What I am reading in)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.*;
import java.io.*;
public class Popcorn {
public static void main (String [] args) throws IOException {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getName();
Scanner infile = new Scanner(new FileReader( filename));
String line = "" ;
while (infile.hasNextLine())
{ line= infile.nextLine();
// int endingIndex =line.indexOf(',');
//String fromName = line.substring(0, endingIndex);
System.out.println(line);}
infile.close();
}
}
Use Integer.parseInt() to know if its a number. Have a catch exception block and if it comes in catch block, you'd know its not a number