Printing unknown number list of words - java

I created a program that checks a text file of how many words of a specific length appear in it. I wanted to print the number of words that my program found of this specific length and then print out that list of words. However, the list of words is printing in my while loop first, because I have to print the count outside of this loop. Do I have to make this unknown numbered list into an array and then return the array to print it in the main method in order for this to print second? Here's what I have so far:
public static void countLetters(PartArray part, int num) throws Exception{
Scanner inputFile = new Scanner(new File("2of12inf.txt"));
int count = 0;
while( inputFile.hasNext() ){
String word = inputFile.next();
if (word.length() == num)
{
count++;
expandArray (part , 2*MAX_SIZE);
System.out.println(word);
}
}
System.out.println("I found " + count + " " + num + "-letter words.");
System.out.println("The list of words is: ");
inputFile.close();

If you want to avoid printing the words in the while loop, you can take the println out of the loop. You don't have to add each word to a data structure if you don't want to. You can append each word to a "wordBuffer" StringBuffer (String Buffer concatenation is faster and more efficient than a String), for more info on this matter read this: http://www.javaworld.com/article/2076072/build-ci-sdlc/stringbuffer-versus-string.html
like this:
int count = 0;
StringBuffer wordBuffer = new StringBuffer ("");
while( inputFile.hasNext() ){
String word = inputFile.next();
if (word.length() == num)
{
count++;
//Adding \n assuming you want new line between elements
wordBuffer.append(word+"\n");
}
}
System.out.println("I found " + count + " " + num + "-letter words.");
System.out.println("The list of words is: "wordBuffer);
inputFile.close();
Is this what you were looking for?

The problem with arrays in this context is an array has an immutable size once initialized. If you're retrieving a mutable collection, you need a collector that has no such limitation. An ArrayList would achieve this.
public static void countLetters(PartArray part, int num) throws Exception {
Scanner inputFile = new Scanner(new File("2of12inf.txt"));
int count = 0;
ArrayList<String> words = new ArrayList();
while( inputFile.hasNext() ){
String word = inputFile.next();
if (word.length() == num)
{
count++;
//expandArray (part , 2*MAX_SIZE);
//System.out.println(word);
words.add(word);//adding each word to a new index with each iteration
}
}
System.out.println("I found " + count + " " + num + "-letter words.");
System.out.println("The list of words is: ");
for (String w in words) {//for each word in the words ArrayList
System.out.println(w);//print out the values
}
inputFile.close();

Related

Using JAVA - How can I compute the total sum of input strings & their lengths without using Array?

I am not getting the correct output... Any help with this function in JAVA?
The expected Output should be:
The total sum of the word lengths entered was: 9 (depending on user
input) The longest word was: Oranges, with length 7 The
shortest word was: Ox, with length 2
Note: No Array is to be used. Thanks
Here's my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
int count = 0;
while (!(line = input.nextLine()).isEmpty())
{
System.out.println("Enter word: ");
count++;
} System.out.println("The total sum of the word lengths entered was: " + count + " words. ");
System.out.println("The longest word was: " input + " with length " + input.length);
System.out.println("The shortest word was: " input + " with length " + input.length);
}
}
In your while block (the lines between the {} pair after while), you have the line that someone entered. It is of type String.
If you look up the String class in Java, you will find that it has a method for length(), so that's how you get the length of the line (line.length() returns an int length).
To track the longest line, you need a variable declared up where count is declared that is going to store the longest line entered. For each line, compare the length of the line you have with the longest length you've encountered so far; if the current one is the longest, then store its length (and its value, if you'll need that also, in a variable declared next to count and the longest line value). The reason I'm pointing out where to put them is that they need to be declared outside the while loop so that you can refer to them after the loop has finished.
Shortest is done the same way, with different variables.
Good luck -- post more questions if you need to! I've tried to give you enough info that you can write the actual code yourself, but it's hard to gauge just how much that is.
it would be something like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
String line;
Scanner input = new Scanner(System.in);
int count = 0;
String shortest = String.format("%0" + 10000 + "d", 0).replace("0", "x");
String longest = "";
while (!(line = input.nextLine()).isEmpty()) {
System.out.println("Enter word: ");
count += line.length();
if (line.length() > longest.length())
longest = line;
if(line.length() < shortest.length())
shortest = line;
}
System.out.println("The total sum of the word lengths entered was: " + count + " words. ");
System.out.println("The longest word was: " + longest + " with length " + longest.length());
System.out.println("The shortest word was: " + shortest + " with length " + shortest.length());
}
}
Set the smallest and largest word sizes based on the first word encountered. Then keep comparing values to determine the sizes. This also handles case if words are the same size.
public static void main(String[] args) {
String line;
Scanner input = new Scanner(System.in);
int count = 0;
int largestSize = 0;
int smallestSize = 0;
String longestWord = "";
String shortestWord = "";
while (!(line = input.nextLine()).isEmpty()) {
System.out.println("Enter word: ");
count++;
//Initialize sizes and words on first round.
if (count == 1) {
smallestSize = largestSize;
shortestWord = line;
}
//Do the comparisons.
if (largestSize <= line.length()) {
largestSize = line.length();
longestWord = line;
} else if (smallestSize > line.length()) {
smallestSize = line.length();
shortestWord = line;
}
}
System.out.println("The total sum of the word lengths entered was: " + count + " words. ");
System.out.println("The longest word was: " + longestWord + " with length " + longestWord.length());
System.out.println("The shortest word was: " + shortestWord + " with length " + shortestWord.length());
}

Program that reads file input and displays proportion of the length of the letter and so on

I have an assignment due two days and I have been trying a lot of days to do this, but I am burned, tried to come back to it, still no progress.
THE ASSIGNMENT is the following:
Java program that computes the above statistics from
any text file. Here’s what it might look like in action:
Name of the input file: example.txt
The proportion of 1-letter words: 3.91% (74 words)
The proportion of 2-letter words: 18.52% (349 words)
The proportion of 3-letter words: 24.24% (456 words)
The proportion of 4-letter words: 19.80% (374 words)
The proportion of 5-letter words: 11.33% (212 words)
…
…
The proportion of 12-letter words: 0.45% (8 words)
Proportion of 13- (or more) letter words: 0.51% (9 words)
Now In order to do this, I thought to divide my program into three methods: Read the method, count the letters and distinguish them and finally display it as the example above. Now that I said that, here is my code right now:
/*like make smaller functions
where each function has one task
like to loop through the file and return an array of words
then use that as input to another function whose purpose is to count the
letters
and then pass that array into a function for printing that.
*/
import java.io.*;
import java.util.Scanner;
class Autorship {
public static void main(String[] args) {
try {
System.out.println("Name of input file: ");
Scanner sc1 = new Scanner(System. in );
sc1.useDelimiter("[^a-zA-Z]");
String fname = sc1.nextLine();
sc1.close();
sc1 = new Scanner(new FileReader(fname));
sc1.useDelimiter("[^a-zA-Z]");
String line;
System.out.println(WordCount(fname, sc1));
} catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
public static int WordCount(String fname, Scanner sc1) {
int wordCount = 0;
int lineCount = 0;
while (sc1.hasNextLine()) {
String line;
line = sc1.nextLine();
lineCount++;
String[] strings = line.split(" ");
int[] counts = new int[14];
for (String str: strings)
if (str.length() < counts.length) counts[str.length()] += 1;
System.out.println("This is counts length: " + counts.length);
for (int i = 1; i < counts.length; i++)
System.out.println(i + " letter words: " + counts[i]);
}
return 0;
}
}
Now please I do not want the answer, as that would be plagiarism, and I am not that kind of person, I just want a bit of help to continue to progress, I'm so stuck right now, thanks ^^
Here is an adjusted and working version. I commented the lines I edited.
Your code wasn't that bad and it was working quite well. The only problem you had was that you've printed out the letter counts inside the while-loop instead of doing it outside. Therefore it repeated with every new line that was read from the file.
Please note: I strongly recommend to always use curly brackets even though Java syntax allows to not use them with if-statements and for-loops if they're followed by only one line of code to execute. But not using them makes the code harder to read and error prone.
public static void main(String[] args) {
try {
System.out.println("Name of input file: ");
Scanner sc1 = new Scanner(System. in );
sc1.useDelimiter("[^a-zA-Z]");
String fname = sc1.nextLine();
sc1.close();
sc1 = new Scanner(new FileReader(fname));
sc1.useDelimiter("[^a-zA-Z]");
String line;
System.out.println("WordCount: " + WordCount(fname, sc1)); // edited
} catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
public static int WordCount(String fname, Scanner sc1) {
int wordCount = 0;
int lineCount = 0;
final int MAXIMUM_LENGTH = 14; // edited. Better use a constant here.
int[] counts = new int[MAXIMUM_LENGTH]; // edited. Constant applied
while (sc1.hasNextLine()) {
String line = sc1.nextLine();
// increment line count
lineCount++;
String[] strings = line.split(" ");
// increment word count
wordCount += strings.length; // added
// edited. curly brackets and constant MAXIMUM_LENGTH
for (String str: strings) {
if (str.length() < MAXIMUM_LENGTH) {
counts[str.length()] += 1;
}
}
}
// edited / added. finally show the results
System.out.println("maximum length: " + MAXIMUM_LENGTH);
System.out.println("line count: " + lineCount);
System.out.println("word count: " + wordCount);
// edited. moved out of the while-loop. MAXIMUM_LENGTH applied.
for (int i = 1; i < MAXIMUM_LENGTH; i++) {
System.out.println(i + " letter words: " + counts[i]);
}
// edited.
return wordCount;
}

FileStatistics -- trouble counting the number of words in a file

In my course, we are tasked with determining three key statistics about a file that is passed via the console input: 1) number of characters, 2) number of lines, 3) number of words. Before closing this question as a duplicate, please read on to see what unique problem I'm encountering. Thank you :)
I originally wrote a solution with three separate methods and three separate Scanner variables, but I realized that for larger files, this solution would be very inefficient. Instead, I decided to write up a solution that only runs through the file a single time and calculates all three statistics in one go. Here is what I have so far:
import java.util.*;
import java.io.*;
public class FileStatistics
{
// Note: uncomment (A) and (B) below to test execution time
public static void main( String [] args ) throws IOException
{
/* (A)
long startTime = System.currentTimeMillis();
*/
File file = new File(args[0]);
Scanner input = new Scanner(file);
int numChars = 0, numWords = 0, numLines = 0;
/* Calculations */
while( input.hasNextLine() )
{
String currentLine = input.nextLine();
numLines++;
numChars+= currentLine.length();
String [] words = currentLine.split(" ");
numWords += words.length;
}
input.close();
/* Results */
System.out.println( "File " + file.getName() + " has ");
System.out.println( numChars + " characters");
System.out.println( numWords + " words");
System.out.println( numLines + " lines");
/* (B)
long endTime = System.currentTimeMillis();
System.out.println("Execution took: " + (endTime-startTime)/1000.0 + " seconds");
*/
}
}
I've been comparing the results of my program to Microsoft Word's own file statistics by simply copy/pasting the contents of whatever file I'm using into Word. The number of characters and number of lines are calculated correctly.
However, my program does not properly count the number of words. I decided to include a test statement in there to print out the contents of the array words, and it seems that certain "spatial formatting" (like tabs from a Java source code file) are being treated as individual elements in the split array. I tried doing currentLine.replace("\t", "") before invoking the split method to remove those tabs, but this didn't change a thing.
Could someone please offer some advice or hints as to what I'm doing wrong?
This is because the String array returned by currentLine.split(" ") can contain elements which are empty Strings: "". You can see this if you call System.out.println(Arrays.toString(words)).
To create the desired behavior, you can store words.length in a variable count and decrement count for each instance of the empty string "" in words.
Here is a sample solution:
while( input.hasNextLine() )
{
String currentLine = input.nextLine();
numLines++;
numChars+= currentLine.length();
String [] words = currentLine.split("\\s+");
int count = words.length;
for (int i = 0; i < words.length; i++) {
if (words[i].equals("")) {
count--;
}
}
numWords += count;
}
Alternatively, you can convert words to an ArrayList and use the removeAll() functions:
while( input.hasNextLine() )
{
String currentLine = input.nextLine();
numLines++;
numChars+= currentLine.length();
ArrayList<String> words = new ArrayList<>(Arrays.asList(currentLine.split("\\s+")));
words.removeAll(Collections.singleton(""));
numWords += words.size();
}

This is only returning the largest letter word, when I want it to return the count for every letter word

I need to get this code to take the user input and tell me how many one-letter words, two-letter words, three-letter words, etc. there are. This code compiles, but it only gives me the number of times the word with the most letters is used. For example, if the user input were "I want to know why this is not working" The output would be one seven-letter word. It doesn't tell me how many times all the other number of letter words are used.
import java.util.*;
import java.io.*;
public class Analysis B { //open class
public static String input;
public static String stringB;
public static void main (String args []) { //open main
System.out.println("Please enter a line of text for analysis:");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
input = input.toLowerCase();
System.out.println("Analysis B:");//Analysis B
System.out.println("Word length: " + " Frequency: ");
System.out.println(AnalysisB(stringB));
} // close main
public static String AnalysisB (String stringB) { // open analysis B
String [] words = input.split(" ");
int largest = 0;
for (int i = 0; i < words.length; i++) { //open for
largest = Math.max( words[i].length(), largest); // get the largest value
} //close for
int [] frequencies = new int[ largest + 1 ];
for (int i = 0; i < words.length; i++) { //open for
frequencies[words[i].length()]++;
} //close for
for (int i = 0; i < frequencies.length; i++) { //open for
if (frequencies[i] > 0 ) { //open if
stringB =(i + "-letter words" + " " + frequencies[i]);
} //close if
} //close for
return stringB;
} // close analysis B
} //close class
Here's your problem:
stringB =(i + "-letter words" + " " + frequencies[i]);
Each time this line of code is run, it assigns a new value to stringB, over-writing the previous value. Instead, you want it to look like this:
stringB += (i + "-letter words" + " " + frequencies[i] + "\n");
The += operator will add to stringB instead of replacing it (and the "\n" will ensure it adds to a new line each time).
By the way, there's no need to import java.io.*, since it isn't used in your program. java.io deals with file operations.
Here's a way to do this with a sorted HashMap (TreeMap):
public static void AnalysisB (String input)
{
String [] words = input.split(" ");
Map<Integer, Integer> map = new TreeMap<Integer, Integer>();
for (String w : words)
{
int len = w.length();
Integer freq = map.get(len);
if (freq == null)
{
map.put(len, 1);
}
else
{
map.put(len, freq + 1);
}
}
for (Iterator<Integer> iter = map.keySet().iterator(); iter.hasNext(); )
{
int len = iter.next();
System.out.println(len + "-letter words" + " " + map.get(len));
}
}
Note: I made the method void since you are just printing out the frequencies in the method.
Try this.
public static String AnalysisB (String stringB) {
return Stream.of(stringB.split(" "))
.map(s -> s.length())
.collect(Collectors.groupingBy(n -> n, Collectors.counting()))
.entrySet().stream()
.sorted(Comparator.comparing(e -> e.getKey()))
.map(e -> e.getKey() + "-letter words " + e.getValue())
.collect(Collectors.joining("\n"));
}
and
System.out.println(AnalysisB("I want to know why this is not working"));
result:
1-letter words 1
2-letter words 2
3-letter words 2
4-letter words 3
7-letter words 1

using string methods to count characters

I'm trying to count the number of non-blank characters in a string.
It works fine when there are no leading blank spaces, but when I add 3 spaces in from, it doubles the number of non-blank characters.
This is my code:
import java.io.*;
import java.util.*;
public class countCharacters
{
public static void main(String[] args) throws Exception
{
String str1;
int count;
count = 0;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a string: ");
str1 = dataIn.readLine();
while(str1.length() > 0)
{
System.out.println("The String ''" + str1 + "''");
System.out.println("has " + str1.length() + " Characters, including all blanks.");
for(int i=0; i < str1.length(); ++i)
if(str1.charAt(i) !=' ')
count++;
str1 = str1.trim();
System.out.println("and " + str1.length() + " Characters, trimmed of leading and trailing blanks.");
System.out.println("and " + count + " non-blank characters.");
System.out.println("");
System.out.print("Enter a string: ");
str1 = dataIn.readLine();
}
System.out.println("Program complete.");
}
}
Are you sure that it doubles the count every time? Maybe this only happens on the second time through the main loop?
You should be resetting count when you enter a new string. Otherwise, you're just adding to the count from the previous time through the main loop. Add a line like count = 0; before the System.out.print("Enter a string: "); at the bottom of the main loop, or declare and initialise count inside the loop, rather than before the loop.
A much cleaner way to do this would be to just make a copy without any spaces and compare the lengths:
String str1 = " the quick brown fox ";
String spaceless = str1.replace(" ", "");
System.out.println("Number of spaces: "+(str1.length() - spaceless.length()));
You could simply do
String temp = str1.replaceAll("\\s+","");
temp.length() will give you the answer.
You can get rid of temp variable if modifying str1 is an option
Have you tried using the static method:
Character.isWhitespace(char ch);
For example,
if(!Character.isWhitespace(str1.charAt(i)))
count++;

Categories

Resources