My output is assuming the whole file is one line - java

public static void main(String args[]) throws FileNotFoundException
{
String inputFileName = "textfile.txt";
printFileStats(inputFileName);
}
public static void printFileStats(String fileName) throws FileNotFoundException
{
String outputFileName = "outputtextfile.txt";
File inputFile = new File(fileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
int lines = 0;
int words = 0;
int characters = 0;
while(in.hasNextLine())
{
lines++;
while(in.hasNext())
{
in.next();
words++;
}
}
out.println("Lines: " + lines);
out.println("Words: " + words);
out.println("Characters: " + characters);
in.close();
out.close();
}
I have a text file containing five lines
this is
a text
file
full of stuff
and lines
The code creates an output file
Lines: 1
Words: 10
Characters: 0
However, if I remove the capability for reading the number of words in the file, it correctly states the number of lines (5). Why is this happening?

Your inner while loop is gobbling up the whole file. You want to count the number of words in each line, right? Try this instead:
while (in.hasNextLine())
{
lines++;
String line = in.nextLine();
for (String word : line.split("\\s"))
{
words++;
}
}
Note that splitting on spaces is a very naive approach to tokenization (word-splitting) and will only work for simple examples like the one you have here.
Of course, you could also do words += line.split("\\s").length; instead of that inner loop.

in.hasNext() and in.next() treat all whitespace characters as word separators, including newline characters. Your inner loop is eating all the newlines as it's counting all the words.

This reads next Token, not the line :
in.next();
So it just read next and next and next and dont care about line ending. Space or \n is considered as white space usually, so methods like this one does not make any difference between them.

The reason is, that hasNext() does not care about line breaks.
So, you are entering the while(in.hasNextLine()) loop, but then you are consuming the whole file with the while(in.hasNext()) loop, resulting in 1 line and 10 words.
-> Check the token consumed by hasNext() for EOL-Characters, then increase line count.
OR:
Use String line = scanner.nextLine() to obtain exactly ONE line, and then use a second scanner to fetch all tokens of that line: scanner2 = new Scanner(line); while(scanner2.hasNext())

Related

Java how to make the given piece display the whole row, not just the last word where it remained

This code finds the first word "horror", but does not show me the whole line, only the word found.
File f = new File("MyFile.txt");
Scanner scan = new Scanner(f);
while (scan.hasNextLine()) {
String str = scan.next();
if (str.contains("horror")) {
System.out.println(str + " este horror");
}
}
Why is that?
The Scanner class has many methods for reading different types, and each has a corresponding hasNext...() method, for example nextInt() and hasNextInt(). You checked hasNextLine(), but used next() which returns the next word instead of nextLine() which returns the next line.
Change your code from:
String str = scan.next(); // read next word ❌
to:
String str = scan.nextLine(); // read next line ✅

Reading int value from text file, and using value to alter file contents to separate text file.(java)

So I'm trying to read input from a text file, store it into variables, and then output an altered version of that text onto a different file using a variable from the file. I'm using Filereader, Scanner, and Printwriter to do this.
I have to store the last line (which is a number) from this text document and use that number to multiply the body of text onto a different file without including the number.
So the text is:
Original file text
And the output is SUPPOSED to be:
desired output
I'm able to retrieve the number and store it into my multiplier variable and retrieve the text into my string BUT it's stored as a single line if I check inside the console:
how the text is stored seen through console
so it outputs like this on the new file:
undesired output
I'm pretty new to Java, forgive me if there are any questions I can't answer that could help solve any issues with my code.
I've tried adding +"\n" to the file output line but no dice. I've also tried adding it to words += keys.nextLine() +"\n", and it separates the lines in the CONSOLE but not the file itself, unfortunately. Am I at least on the right track?
Here's my code:
public class fileRead {
public static void main(String[] args) throws IOException{
String words = "" ; //Stores the text from file
int multiplier = 1; // Stores the number
FileReader fr = new FileReader("hw3q3.txt");
Scanner keys = new Scanner(fr);
//while loop returns true if there is another line of text will repeat and store lines of text until the last line which is an int
while(keys.hasNextLine())
if (keys.hasNextInt()) { //validation that will read lines until it see's an integer and stores that number
multiplier = keys.nextInt(); //Stores the number from text
} else {
words += keys.nextLine();//Stores the lines of text
keys.nextLine();
}
keys.close();
PrintWriter outputFile = new PrintWriter("hw3q3x3.txt");
for(int i = 1; i <= multiplier; i++) {
outputFile.println(words);
}
outputFile.close();
System.out.println("Data Written");
System.out.println(multiplier);//just to see if it read the number
System.out.println(words); //too see what was stored in 'words'
}
}
See the if-statement below:
words += keys.nextLine(); //Stores the lines of text
if(words.endsWith(words.substring(words.lastIndexOf(" ")+1))) { //detect last word in sentence
words += '\n'; //after last word, append newline
}
...
for(int i = 1; i <= multiplier; i++) {
outputFile.print(words); //change this to print instead of println
}
Basically, after the last word in the sentence within the file we want to append a newline character to start writing the next sentence from new line.
The above if-statement detects the end of the sentence by determining the last word within the words String, and then appending a newline character to the words String. This will yield the result that you are expecting.
Breaking down the expression for you:
words.substring(words.lastIndexOf(" ")+1)
Return the part of the String (substring) that is located at the index of the last whitespace in the String plus 1 (lastIndexOf(" ") + 1) - i.e. we're getting the word after the last whitespace, so the last word.
Entire while-loop:
while(keys.hasNextLine()) {
if (keys.hasNextInt()) { //validation that will read lines until it see's an integer and stores that number
multiplier = keys.nextInt(); //Stores the number from text
} else {
words += keys.nextLine();//Stores the lines of text
if(words.endsWith(words.substring(words.lastIndexOf(" ")+1))) {
words += '\n';
}
}
}

ArrayList: Get length of longest string, Get average length of string

In Java, I have a method that reads in a text file that has all the words in the dictionary, each on their own line.
It reads each line by using a for loop and adds each word to an ArrayList.
I want to get the length of the longest word (String) in the Array. In addition, I want to get the length of the longest word in the dictionary file. It would probably be easier to split this into several methods, but I don't know the syntax.
So far, the code is have is:
public class spellCheck {
static ArrayList <String> dictionary; //the dictonary file
/**
* load file
* #param fileName the file containing the dictionary
* #throws FileNotFoundException
*/
public static void loadDictionary(String fileName) throws FileNotFoundException {
Scanner in = new Scanner(new File(fileName));
while (in.hasNext())
{
for(int i = 0; i < fileName.length(); ++i)
{
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
Assuming that each word is on it's own line, you should be reading the file more like...
try (Scanner in = new Scanner(new File(fileName))) {
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
Remember, if you open a resource, you are responsible for closing. See The try-with-resources Statement for more details...
Calculating the metrics can be done after reading the file, but since your here, you could do something like...
int totalWordLength = 0;
String longest = "";
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
totalWordLength += dictionaryword.length();
dictionary.add(dictionaryword);
if (dictionaryword.length() > longest.length()) {
longest = dictionaryword;
}
}
int averageLength = Math.round(totalWordLength / (float)dictionary.size());
But you could just as easily loop through the dictionary and use the same idea
(nb- I've used local variables, so you will either want to make them class fields or return them wrapped in some kind of "metrics" class - your choice)
Set a two counters and a variable that holds the current longest word found before you start reading in with your while loop. To find the average have one counter be incremented by one each time the line is read and have the second counter add up the total number of characters in each word (obviously the total number of characters entered, divided by the total number of words read -- as denoted by the total number of lines -- is the average length of each word.
As for the longest word, set the longest word to be the empty string or some dummy value like a single character. Each time you read in a line compare the current word with the previously found longest word (using the .length() method on the String to find its length) and if its longer set a new longest word found
Also, if you have all this in a file, I'd use a buffered reader to read in your input data
May be this could help
String words = "Rookie never dissappoints, dont trust any Rookie";
// read your file to string if you get string while reading then you can use below code to do that.
String ss[] = words.split(" ");
List<String> list = Arrays.asList(ss);
Map<Integer,String> set = new Hashtable<Integer,String>();
int i =0;
for(String str : list)
{
set.put(str.length(), str);
System.out.println(list.get(i));
i++;
}
Set<Integer> keys = set.keySet();
System.out.println(keys);
System.out.println(set);
Object j[]= keys.toArray();
Arrays.sort(j);
Object max = j[j.length-1];
set.get(max);
System.out.println("Tha longest word is "+set.get(max));
System.out.println("Length is "+max);

While loops aren't repeating

This program will read each phone number from the telephones.txt file and will check if it can be translated into one or more words of words.txt file. The output of the program will contain the telephone numbers and their word representatives. (assuming there are words and phones in the file)
public static void main(String[] args) throws IOException
{
Scanner phones = new Scanner(new File("phones.txt"));
Scanner words = new Scanner(new File("words.txt"));
PrintWriter outfile = new PrintWriter(new FileWriter("outfile.txt"));
String number = "", output = "", code = "" ;
//Scans for next phone string
while(phones.hasNext())
{
number = phones.next();
number = number.replace("-","");
//Scans for next word string
while(words.hasNext())
{
code = words.next();
char[] wordChars = null;
wordChars = code.toCharArray();
output = "";
//converts word to digits
for(char wordChar : wordChars)
{
output = output.concat(new String(convert(wordChar)));
}
if(number.equals(output));
{
System.out.println(number + " " + code);
}
break;
}
}
}
This is what I have done so far, except I can't figure out something
if(number.equals(output));
{
System.out.println(number + " " + code);
}
For this line Im trying to see if the output has the same value as the number and if it does have the same value I want to print it out however this is what happens in my program.
I tried tracing my program and this is what i think is happening but its not...
Enter first while loop while theres a phone string continue
Set number to next phone string
Enter 2nd while loop while theres a word string continue
Set code to the CURRENT word string and convert it to a digit value (assume the conversion is correct)
If converted string isn't equal to number I want to continue the loop and search for the next word. And if it is I want to display number + code and continue searching for more words.
After i search through the list of words I want to continue to the next number and repeat the search for words for that number until the first while loop has no more numbers
Answering your second issue:
After i search through the list of words I want to continue to the
next number and repeat the search for words for that number until the
first while loop has no more numbers
Answer:
You should create a new instance if scanner in each iteration, i.e. move the line:
Scanner words = new Scanner(new File("words.txt"));
into the body of the outer loop.
while(phones.hasNext())
{
Scanner words = new Scanner(new File("words.txt"));
number = phones.next();
number = number.replace("-","");
//Scans for next word string
while(words.hasNext())
{
...
}
}
Your inner loop always ends on a break. So the loop body will only ever get executed once. Just put your break into the block that describes the handling of a successful phone number match.

Read and split a text file (java)

I have some text files with time information, like:
46321882696937;46322241663603;358966666
46325844895266;46326074026933;229131667
46417974251902;46418206896898;232644996
46422760835237;46423223321897;462486660
For now, I need the third column of the file, to calculate the average.
How can I do this? I need to get every text lines, and then get the last column?
You can read the file line by line using a BufferedReader or a Scanner, or even some other techinique. Using a Scanner is pretty straightforward, like this:
public void read(File file) throws IOException{
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
System.out.println(scanner.nextLine());
}
}
For splitting a String with a defined separator, you can use the split method, that recevies a Regular Expression as argument, and splits a String by all the character sequences that match that expression. In your case it's pretty simple, just the ;
String[] matches = myString.split(";");
And if you want to get the last item of an array you can just use it's length as parameter. remembering that the last item of an array is always in the index length - 1
String lastItem = matches[matches.length - 1];
And if you join all that together you can get something like this:
public void read(File file) throws IOException{
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
String[] tokens = scanner.nextLine().split(";");
String last = tokens[tokens.length - 1];
System.out.println(last);
}
}
Yes you have to read each line of the file and split it by ";" separator and read third element.

Categories

Resources