Java simple counting words in a file - java

I am creating a simple program that counts the number of words, lines and total characters (not including whitespace) in a paper. It is a very simple program. My file compiles but when I run it I get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at WordCount.wordCounter(WordCount.java:30)
at WordCount.main(WordCount.java:16)
Does anyone know why this is happening?
import java.util.*;
import java.io.*;
public class WordCount {
//throws the exception
public static void main(String[] args) throws FileNotFoundException {
//calls on each counter method and prints each one
System.out.println("Number of Words: " + wordCounter());
System.out.println("Number of Lines: " + lineCounter());
System.out.println("Number of Characters: " + charCounter());
}
//static method that counts words in the text file
public static int wordCounter() throws FileNotFoundException {
//inputs the text file
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
//while there are more lines
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
return countWords;
}
//static method that counts lines in the text file
public static int lineCounter() throws FileNotFoundException {
//inputs the text file
Scanner input2 = new Scanner(new File("words.txt"));
int countLines = 0;
//while there are more lines
while (input2.hasNextLine()) {
//casts each line as a string
String line = input2.nextLine();
//counts each line
countLines++;
}
return countLines;
}
//static method that counts characters in the text file
public static int charCounter() throws FileNotFoundException {
//inputs the text file
Scanner input3 = new Scanner(new File("words.txt"));
int countChar = 0;
int character = 0;
//while there are more lines
while(input3.hasNextLine()) {
//casts each line as a string
String line = input3.nextLine();
//goes through each character of the line
for(int i=0; i < line.length(); i++){
character = line.charAt(i);
//if character is not a space (gets rid of whitespace)
if (character != 32){
//counts each character
countChar++;
}
}
}
return countChar;
}
}

I can't really say the exact reason for the problem without looking at the file (Maybe even not then).
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
Is your problem. If you are using the input.hasNextLine() in the while conditional statement use input.nextLine(). Since you are using input.next() you should use input.hasNext() in the while loops conditional statement.

public static int wordCounter() throws FileNotFoundException
{
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
while (input.hasNextLine()) {
if(input.hasNext()) {
String word = input.next();
countWords++;
}
}
return countWords;
}
I have just added an if condition within the while loop. Just make sure to check there are token to be parsed. I have changed only in this place. Just make sure to change wherever needed.
This link will give good info. in regard to that.
Hope it was helpful. :)

Related

Word Anagram not getting all user input

I am writing a program checking if n words are anagrams of the initially given word. It the word is an anagram it prints "yes", if it isn't - prints "no". It solves the problem correctly if I input all the data manually in the console. If I copy and paste the data it does not "see" the last line until I hit enter again. So it I paste the following input:
anagram
6
gramana
aaagrnm
anagra
margana
abc
xy
So I get only 5 yes-es and no-s and when I hit enter again I get the last no.
here is my code
import java.util.Scanner;
import java.util.Arrays;
public class WordAnagrams {
public static void anagramCheck (String x, String y) {
char[] initial= new char[x.length()];
for (int i=0; i<x.length(); i++) {
initial[i]=x.charAt(i);
}
Arrays.sort(initial);
char[] isAnagram = new char[y.length()];
for (int i=0; i<y.length(); i++) {
isAnagram[i]=y.charAt(i);
// System.out.println(isAnagram[i]);
}
Arrays.sort(isAnagram);
boolean same=Arrays.equals(initial, isAnagram);
if (same) {
System.out.println ("yes");
}
else {
System.out.println ("no");
}
// return answer;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String word = input.nextLine();
int n = Integer.parseInt(input.nextLine());
String anagram=""; // input.nextLine();
// int counter=0;
System.out.println();
/* while (counter<n+1) {
anagram=input.nextLine();
anagramCheck(word, anagram);
// anagram=input.nextLine();
counter++;
}*/
for (int i=0; i<=n; i++) {
anagram=input.nextLine();
anagramCheck(word, anagram);
// anagram=input.nextLine();
// System.out.println(answers[i]);
}
System.out.println();
}
}
The issue is that when you copy paste the input, the last word have no '\n' at the end so the scanner doesn't read this as a line until you press ENTER.
So what I can propose is:
1) Use a File for an Input
Or 2) Use InputStreamReader to fetch from the console. Here is some code to do it:
`
public static void main(String[] args) throws IOException {
char buffer[] = new char[512];
InputStreamReader input = new InputStreamReader(System.in);
input.read(buffer,0,512);
String data[] = (new String(buffer)).split("\n");
}
`
It give you a list of strings at the end. PS: Your loop "for(int i =0;i<=n;i++)" is looping 7 times with n = 6.
#kalina199
You could also shorten your code a bit to save yourself from defining a method to check the input from the console.
I did it by splitting the console input into a String array using a simple regex and immediately sorted it.
Then my loop does a simple check to compare the new user input to the original word by their lengths and if that doesn't match you just print out "no" and continue with the next word.
Here's my code:
package bg.Cholakov;
import java.util.Arrays;
import java.util.Scanner;
public class Anagram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] initWord = scanner.nextLine().split("");
Arrays.sort(initWord);
int num = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < num; i++) {
String[] testWord = scanner.nextLine().split("");
Arrays.sort(testWord);
if (!(initWord.length == testWord.length)) {
System.out.println("no");
} else if (initWord[i].equals(testWord[i])) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}

Words and lines counter from user input for Java

I have done this code, it prints correctly the total number of lines but for the total number of words it always prints total of 1 word. Can someone help me please, Thanks!
import java.util.*;
public class LineAndWordCounter{
public static void main(String[]args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String line = scan.next();
linesCounter(scan);
wordsCounter(new Scanner(line) );
}
}
public static void linesCounter(Scanner linesInput){
int lines = 0;
while(linesInput.hasNextLine()){
lines++;
linesInput.nextLine();
}
System.out.println("lines: "+lines);
}
public static void wordsCounter(Scanner wordInput){
int words = 0;
while(wordInput.hasNext()){
words++;
wordInput.next();
}
System.out.println("Words: "+words);
}
}
This looks rather complicated to me.
You can just save each line in an ArrayList and accumulate the words in a variable.
Something like this:
List<String> arrayList = new ArrayList<>();
int words = 0;
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
String line = scan.nextLine();
arrayList.add(line);
words += line.split(" ").length;
System.out.println("lines: " + arrayList.size());
System.out.println("words: " + words);
}
scan.close();
You should also not forget to call the close() method o the Scanner to avoid a resource leak
scan.next()
returns the next "word".
If you create a new Scanner out of that one word, it will only ever see one word.
This will happen with
String line = scan.next();
wordsCounter(new Scanner(line) );

How to Extract Multiple words from a string using IndexOf and substring Java?

I have a file i imported through system, Now i am stuck. Using while loops and if statements, and WITHOUT the help of the Split() method, How could i first, Read the file, line by line with the scanner? Then second how could i pull the words out one by one, As i pull out one word, A variable, countWords has to increase by one, say there is 5 words in a string, I would need to run through the loop 5 times and countWords would become 5.
This is the code i have so far, Kind of crappy.
import java.util.Scanner;
import java.io.*;
class Assignmentfive
{
private static final String String = null;
public static void main(String[] args) throws FileNotFoundException
{
Scanner scan = new Scanner(new File("asgn5data.txt"));
int educationLevel = 0;
String fileRead = "";
int wordCount = 0;
while (scan.hasNext() && !fileRead.contains("."))
{
fileRead = scan.nextLine();
int index = fileRead.indexOf(" ");
String strA = fileRead.substring(index);
System.out.print(strA);
wordCount++;
}
There is more to my code, however it is just a few calculations commented out.
Thanks!
Here is how I would refactor your while loop to correctly extract, print, and count all words in a sentence:
while (scan.hasNext()) {
int wordCount = 0;
int numChars = 0;
fileRead = scan.nextLine();
// Note: I add an extra space at the end of the input sentence
// so that the while loop will pick up on the last word.
if (fileRead.charAt(fileRead.length() - 1) == '.') {
fileRead = fileRead.substring(0, fileRead.length() - 1) + " ";
}
else {
fileRead = fileRead + " ";
}
int index = fileRead.indexOf(" ");
do {
String strA = fileRead.substring(0, index);
System.out.print(strA + " ");
fileRead = fileRead.substring(index+1, fileRead.length());
index = fileRead.indexOf(" ");
wordCount++;
numChars += strA.length();
} while (index != -1);
// here is your computation.
if (wordCount > 0) {
double result = (double)numChars / wordCount; // average length of words
result = Math.pow(result, 2.0); // square the average
result = wordCount * result; // multiply by number of words
System.out.println(result); // output this number
}
}
I tested this code by hard-coding the string fileRead to be your first sentence The cat is black.. I got the following output.
Output:
The
cat
is
black

How to count the amount of times a word shows up in text file in Java?

So I'm pretty new to Java and I'm working on a code that is supposed to read a .txt file that the user inputs and then ask the user for a word to search for within the .txt file. I'm having trouble figuring out how to count the amount of times the inputted word shows up in the .txt file. Instead, the code I have is only counting the amount of lines the code shows up in. Can anyone help me figure out what to do to have my program count the amount of times the word shows up instead of the amount of lines the word shows up in? Thank you! Here's the code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextSearch {
public static void main(String[] args) throws FileNotFoundException {
Scanner txt;
File file = null;
String Default = "/eng/home/tylorkun/workspace/09.1/src/Sample.txt";
try {
txt = new Scanner(System.in);
System.out.print("Please enter the text file name or type 'Default' for a default file. ");
file = new File(txt.nextLine());
txt = new Scanner(file);
while (txt.hasNextLine()) {
String line = txt.nextLine();
System.out.println(line);
}
txt.close();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
txt = new Scanner(file);
Scanner in = new Scanner(System.in);
in.nextLine();
System.out.print("Please enter a string to search for. Please do not enter a string longer than 16 characters. ");
String wordInput = in.nextLine();
//If too long
if (wordInput.length() > 16) {
System.out.println("Please do not enter a string longer than 16 characters. Try again. ");
wordInput = in.nextLine();
}
//Search
int count = 0;
while (txt.hasNextLine()) //Should txt be in?
{
String line = txt.nextLine();
count++;
if (line.contains(wordInput)) //count > 0
{
System.out.println("'" + wordInput + "' was found " + count + " times in this document. ");
break;
}
//else
//{
// System.out.println("Word was not found. ");
//}
}
} catch (FileNotFoundException e) {
System.out.println("Word was not found. ");
}
} //main ends
} //TextSearch ends
Since the word doesn't have to be standalone, you can do an interesting for loop to count how many times your word appears in each line.
public static void main(String[] args) throws Exception {
String wordToSearch = "the";
String data = "the their father them therefore then";
int count = 0;
for (int index = data.indexOf(wordToSearch);
index != -1;
index = data.indexOf(wordToSearch, index + 1)) {
count++;
}
System.out.println(count);
}
Results:
6
So the searching segment of your code could look like:
//Search
int count = 0;
while (txt.hasNextLine())
{
String line = txt.nextLine();
for (int index = line.indexOf(wordInput);
index != -1;
index = line.indexOf(wordInput, index + 1)) {
count++;
}
}
System.out.println(count);
Your problem is that you are incrementing count on each line, regardless of whether the word is present. Also, you have no code to count multiple matches per line.
Instead, use a regex search to find the matches, and increment count for each match found:
//Search
int count = 0;
Pattern = Pattern.compile(wordInput, Pattern.LITERAL | Pattern.CASE_INSENSITIVE);
while(txt.hasNextLine()){
Matcher m = pattern.matcher(txt.nextLine());
// Loop through all matches
while (m.find()) {
count++;
}
}
NOTE: Not sure what you are using this for, but if you just need the functionality you can combine the grep and wc (wordcount) command-line utilities. See this SO Answer for how to do that.

Using four methods to count and display the lines, words, and characters in a file in java

This is my first time using more than one method in a progam and I have also never tried to count lines, words and letters in a file. So I've read three Java books file sections and then looked at questions on the forum here and had a go. I think I am doing something wrong with variable names, as I don't know the rules with where you put them in in multi method etc. If you could say something like that is glaringly wrong because you have to do this, that would be helpful. I can't use the debugger because I can't compile it. Anyway, thanks for looking at this.
import java.util.Scanner;
import java.io.*;
/**
* A program to count the number of lines, words and characters in a text file.
*
* #author
* #version 2014
*/
public class WordCount
{
public static void main(String[] args) throws FileNotFoundException
{
// get the filename
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
lines(filename);
words(filename);
characters(filename);
}
/**
* Count the number of lines in a file, and print out the result.
*
*/
public static void lines(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
file.nextLine();
}
return lines;
inputFile.close();
}
/**
* Count the number of words in a file, and print out the result.
*
*/
public static void words(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (input.hasNextLine())
{
String word = input.next();
words++;
}
return words;
inputFile.close();
}
/**
* Count the number of characters in a file, and print out the result.
*
*/
public static void characters(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{ characters = line.charAt(i);
if (character != 32)
{
characters++;
}
}
}
return characters;
inputFile.close();
System.out.println("The number of lines is: " + lines);
System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + characters);
System.out.println();
}
}
Change the following
public static int lines(String filename) throws FileNotFoundException
//change the return type to int instead of void
{
Scanner inputFile = new Scanner(filename); //filename instead of file
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine(); // ---do----
}
inputFile.close(); // after return it will become unreachable
return lines;
}
Same applies to other methods
Your code contains several problems. So let us fix that one by one in each method:
public static void main(String[] args) throws FileNotFoundException
{
// get the filename
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of the file: ");
String filename = keyboard.nextLine();
keyboard.close(); // <- don't forget to close this resource
File file = new File(filename);
//Scanner inputFile = new Scanner(file); // <- this line is unnecessary, because you never use that variable
lines(file); // <- you already obtained a File object, so use it ;)
words(file);
characters(file);
}
Next method:
public static void lines(File file) throws FileNotFoundException // mind the new argument type
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine(); //<- use "inputFile" instead of "file"
}
inputFile.close();
//return lines; // <- you can't return something if your method uses "void" as the return type
//your comment on that method says that you like to print the result, so let's do that
System.out.println("The number of lines is: " + lines);
}
And the next one:
public static void words(File file) throws FileNotFoundException // <- new argument type
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (inputFile.hasNextLine())
{
//String word = inputFile.next(); // that won't work like you think, but we can do a little "trick" here
String line = inputFile.nextLine(); // read the current line of text
words += line.split(" ").length; // split the line using whitespace and add the number of words to the current value of variable "words"
//words++; // <- not needed anymore
}
//return words; // <- like before: not possible if return type is void
inputFile.close();
//your comment on that method says that you like to print the result, so let's do that
System.out.println("The number of words is: " + words);
}
And the last method:
public static void characters(File file) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
int count = 0; // new variable to count the characters
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{
characters = line.charAt(i); // <- no harm in using a new line :)
if (characters != 32) // <- you wrote "character"
{
count++; // <- "characters" is the current character itself, we won't increase that. For example "a" would become "b" and we don't want/need that :)
}
}
}
//return characters; // <- you know that already ...
inputFile.close();
//System.out.println("The number of lines is: " + lines); // <- "lines" and "words" are unknown here, but we printed these results already
//System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + count); // <- print the count of characters
System.out.println();
}
After this changes you code should work now :).
It seems the methods only need the File object.
int n = countLines(file);
System.out.println("Lines: " + n);
...
public static int countLines(File textFile) throws IOException
{
Scanner inputFile = new Scanner(textFile);
int lines = 0
while (inputFile.hasNextLine())
{
lines++;
inputFile.nextLine();
}
inputFile.close();
return lines;
}
For nextLine you asked the wrong object, Scanner needed.
return returns from the method, so close has come before.
As you return the line count, you must return int.
Method names contain a verb by convention.
The method knows no file or filename.
It also cannot alter a variable if you pass a variable, like file,
You can give the new paramaeter the same name, but for clarity not done here.
Problem number 1:
public static void lines(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int lines = 0;
while (inputFile.hasNextLine())
{
lines++;
file.nextLine();
}
return lines; // <----------------
inputFile.close();
}
This is a void method but you have a return lines statement. Either remove it or change the method header to public static int lines(String filename) throws FileNotFoundException
Problem number 2
public static void words(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int words = 0;
while (input.hasNextLine())
{
String word = input.next();
words++;
}
return words; <-------------
inputFile.close();
}
Again here you ask from a void method to return a value. Change method header to public static int words(String filename) throws FileNotFoundException
Problem number 3:
public static void characters(String filename) throws FileNotFoundException
{
Scanner inputFile = new Scanner(file);
int characters = 0;
while (inputFile.hasNextLine())
{
String line = inputFile.nextLine();
for(int i = 0; i < line.length(); i++)
{ characters = line.charAt(i);
if (character != 32)
{
characters++;
}
}
}
return characters; //<---------------
inputFile.close();
System.out.println("The number of lines is: " + lines);
System.out.println("The number of words is: " + words);
System.out.println("The number of characters is: " + characters);
System.out.println();
}
Again here you have a return int statement on a void method. Just change the method header to this: public static int characters(String filename) throws FileNotFoundException

Categories