Importing text file and doubling array - java

I'm trying to write a method that imports a text file of a very large quantity of words, and then find words of a certain length and print them out.
I'm not looking for code, but rather a clarification if I'm correctly understanding what I'm trying to accomplish.
So, I'm going to import the text using throw exception, and take the number of letters of a specific word:
public static void name(int size) throws Exception{
Scanner inputFile = new Scanner(new File("2of12inf.txt"));
And then create a new array list:
int[] list = new int[MAX_SIZE]; //MAX_SIZE is initially a small number, say 100
int listSize = 0;
Where if the size of the list of words exceeds my MAX_SIZE array, then I'm going to copy the existing array and double it, in order to have the numbers of words fit in the list.
if (listSize == list.length)
{
int[] temp = new int [2*list.length];
for(int i = 0; i < list.length; i++){
temp[i] = list[i];}
list = temp;
}
list[listSize] = size;
listSize++;
inputFile.close();}
This is my raw understanding of how I'm suppose to write the method, is this the correct thinking of just being able to read in words and give a list of them?
EDIT: Sorry, I didn't mention that I'm not to use ArrayLists.

If you know which length you are interested in when before you run the program is suffices to just save those words while you iterate through the words.
Like this I mean:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.SortedSet;
import java.util.TreeSet;
public class WordLengthPrinter {
public static void main(String[] args) throws Exception {
if (args.length != 2)
throw new IllegalArgumentException("Specify filename as first parameter. Word length is second.");
final String fileName = args[0]; // file name is first input argument
final int wordLength = Integer.parseInt(args[1]); // the desired wordlength is second argument
// lets store the words of correct size in a sorted set
SortedSet<String> wordsOfDesiredLength = new TreeSet<String>();
// read file line by line while checking word lengths and only store words of correct length
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
String line = null;
while ( (line = reader.readLine()) != null) {
if (line.length() == wordLength) wordsOfDesiredLength.add(line);
}
}
// print resulting words
for (String word : wordsOfDesiredLength) {
System.out.println(word);
}
}
}

Related

Java scanner reading null from my text file?

I'm writing some code to read an input file of book titles, and putting the read lines into an array and trying to print out the array. But when I try to print out the array, it just returns 'null' for each read line. I'm not sure what I'm doing wrong or what my code is doing. Any suggestions? Thanks!
Code:
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
public static void main(String args[]) throws IOException{
int lineCount = 0;
File inputFile = new File("bookTitles.inp.txt");
Scanner reader = new Scanner(inputFile);
while(reader.hasNextLine()) {
reader.nextLine();
lineCount++;
}
String[] bookArray = new String[lineCount];
while (reader.hasNextLine()) {
for (int i = 0; i < lineCount; i++) {
bookArray[i] = reader.next();
}
}
for (int k = 0; k < lineCount; k++) {
System.out.println(bookArray[k]);
}
reader.close();
inputFile.close();
}
}
My text file I'm reading from is 20 book titles, all on different lines.
My output on the terminal is 20 lines of null.
Lets break this down:
This reads every line of the input file, counts each one, and then discards them:
while(reader.hasNextLine()) {
reader.nextLine();
lineCount++;
}
You are now at the end of file.
Allocate a string array that is large enough.
String[] bookArray = new String[lineCount];
Attempt to read more lines. The loop will terminate immediately because reader.hasNextLine() will return false. You are already at the end of file.
So you the statement assigning to bookArray[i] won't be executed.
while (reader.hasNextLine()) {
for (int i = 0; i < lineCount; i++) {
bookArray[i] = reader.next();
}
}
Since bookArray[i] = ... was never executed above, all of the array elements will still be null.
for (int k = 0; k < lineCount; k++) {
System.out.println(bookArray[k]);
}
One solution is to open and read the file twice.
Another solution is to "reset" the file back to the beginning. (A bit complicated.)
Another solution would be to use a List rather than an array so that you don't need to read the file twice.
Another solution is to search the javadocs for a method that will read all lines of a file / stream as an array of strings.
(Some of these may be precluded by the requirements of your exercise. You work it out ... )
The nested loop in step 3 is also wrong. You don't need a for loop inside a while loop. You need a single loop that "iterates" the over the lines and also increments the array index (i). They don't both need to be done by the loop statement itself. You could do one or the other (or both) in the loop body.
Stephen C has already pointed out the main problems with your logic. You're trying to loop twice through the file but you've already reached the end of the file the first time. Don't loop twice. "Merge" both the while loops into one, remove that for loop inside the while loop and collect all the book titles. You can then use the size of the list to print them later on. My Java might be rusty but here it goes -
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
public static void main(String args[]) throws IOException {
// int lineCount = 0; - You don't need this.
File inputFile = new File("bookTitles.inp.txt");
Scanner reader = new Scanner(inputFile);
// Use an array list to collect book titles.
List<String> bookArray = new ArrayList<>();
// Loop through the file and add titles to the array list.
while(reader.hasNextLine()) {
bookArray.add(reader.nextLine());
// lineCount++; - not needed
}
// Not needed -
// while (reader.hasNextLine()) {
// for (int i = 0; i < lineCount; i++) {
// bookArray[i] = reader.next();
// }
// }
// Use the size method of the array list class to get the length of the list
// and use it for looping.
for (int k = 0; k < bookArray.size(); k++) {
System.out.println(bookArray[k]);
}
reader.close();
inputFile.close();
}
}
I agree with Stephen C. In particular, using a List is usually better than an array because it's more flexible. If you need an array, you can always use toArray() after the List is filled.
Are your book titles on separate lines? If so you might not need a Scanner class, and could use something like a BufferedReader or LineNumberReader.

How to count length of words in a File? Java

I am trying to write a code which would count the number of words of a certain length in a file.
For example:
How are you?
would print:
Proportion of 3-letter words: 100% (3 words)
I want to count words of length 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13+
Can you please guide me?
I am NOT trying to find the number of words. I am already able to do with this code:
public static int WordCount() throws FileNotFoundException
{
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
count++;
}
return count;
}
I want to find words of a certain length.
UPDATE
I have written the following code:
public static int WordLengthCount() throws FileNotFoundException
{
File file = new File("hello.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count5 = 0;
int hell = 0; //This is just for the else command to compile
while(keyboard.hasNext())
{
if ( keyboard.next().length() == 5 )
{
count5++;
keyboard.next();
return count5;
}
} return hell;
}
You can use the length() method to count the number of characters in a string (word). From there on, it's just a matter of saving it somewhere. E.g., in Map:
public static Map<Integer, Integer> lengthCounts() throws FileNotFoundException
Map<Integer, Integer> countMap = new HashMap<>();
while(keyboard.hasNext())
{
String word = keyboard.next();
int length = word.length();
Integer currCount = countMap.get(length);
if (currCount == null) {
countMap.put (length, 1);
else {
countMap.put (length, currCount + 1);
}
}
return countMap;
}
Now you could check the number of words with any particular length, or even print all of them.
EDIT:
If the only thing you need is the percentage of words of a certain length, all you need are two counters - one for the words of that length, and one for all the words:
public static double lengthPercentage(int requiredLength) throws FileNotFoundException
int allWords = 0;
int requiredWords = 0;
while(keyboard.hasNext())
{
String word = keyboard.next();
int length = word.length();
if (length == requiredLength) {
++requiredWords;
}
++allWords;
}
// implicit assumption: there's at least on word in the file
return ((double) requiredWords) / allWords;
}
File file = new File("sample.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
int count=0;
while(keyboard.hasNext())
{
keyboard.next();
// Use a hash map
// Check the string length and add it to the hash map by checking it already exists. If already exists then get the actual value from hashmap and increment it by one and save it again to the map.
count++;
}
So that your final output will be of map with one letter string count, two letter string count etc..
The other answers are great, but if you are trying to find words of a specific length in a file and you don't like the answers above, then you could also try REGEX. You can test each word and then do what you want with it. If you are looking for a count of words in a file of each length, I think the answer above is better, but if you're looking to detect a word of a specific length you could use .length() or the regex below. Using a strings .lenght() function in my opinion is better, but I'm just giving you an alternative answer and example.
I'll put a small example below.
public class Words{
public static void main(String [] args){
String [] words = {"Pizzaaa", "Pizza", "Party"};
int fives = 0;
for( String s : words){
if(s.matches(".{5}")){
5++;
}
}
System.out.println(fives);
}
}
Or a better version:
public class Words{
public static void main(String [] args){
String [] words = {"Pizzaaa", "Pizza", "Party"};
int fives = 0;
for( String s : words){
if(s.length() == 5){
5++;
}
}
System.out.println(fives);
}
}
Edited Below: To demonstrate how it can be used in a file based loop
// other code needed
while(in.hasNext())
{
String s = in.next();
if(s.length() == 5)
fives++;
}
For example, I have text file named TextFile.txt at C:\ has content:
Ut porttitor libero sodales quam sagittis, id facilisis lectus semper.
and Java code:
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
File file = new File("C:\\TextFile.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
if (dis.available() != 0) {
// Get the line.
String s = dis.readLine();
// Put words to array.
String[] sParts = s.split(" ");
// Initialize word longest length.
int longestLength = 1;
for (String strx : sParts) { // Go through each sPart, the next one is called strx
// If the document has word longer than.
if (longestLength < strx.length())
// Set new value for longest length.
longestLength = strx.length();
}
// Because array index from "0".
int[] counts = new int[longestLength + 1];
for (String str : sParts) {
// Add one to the number of words that length has
counts[str.length()] += 1;
}
// We use this type of loop since we need the length.
for (int i = 1; i < counts.length; i++) {
System.out.println(i + " letter words: " + counts[i]);
}
}
}
}
// Result:
// 1 letter words: 0
// 2 letter words: 2
// 3 letter words: 0
// 4 letter words: 1
// 5 letter words: 0
// 6 letter words: 2
// 7 letter words: 2
// 8 letter words: 0
// 9 letter words: 3

Reading text File and putting it in a array

I am trying to take a set of 25 numbers from a text file and convert it into a array. But I am lost.
I have read some other questions similar to this, but all of them used imports and extras, and I don't want to use any imports besides import java.io.*; nor any list.
Also the for loop within this is method is me just messing with it, because I couldn't figure it out.
public static int[] processFile (String filename) throws IOException, FileNotFoundException {
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
while (( line = inputReader.readLine()) != null){
int intValue = Integer.parseInt(line); //converts string into int
for (int i = 0; i < a.length; i++){
a[intValue]++;
}
}
return a;
}
public static void printArray (int[] a) {
for (int i = 0; i<a.length; i++) {
System.out.println (a[i]);
}
}
public static void main(String[] args) throws IOException, FileNotFoundException {
int [] array = processFile("C:\Users\griff_000\Desktop\TestWeek13.txt");
printArray(array);
}
I'm unclear about your whole import restriction, why exactly are you trying to limit the number of imports you have?
Anyway, looking at your code, it seems like the concept of arrays isn't all that clear with you.
Arrays are accessed under the syntax:
array[index] = value;
looking at your code, the line a[intValue]++; is actually finding the array index intValue (the number read from file) and incrementing it by one. Not only is this not what you want, numbers over the array length will cause an ArrayIndexOutOfBoundsException.
Making said amendments we get:
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
int i = 0; // We need to maintain our own iterator when using a while loop
while((line = inputReader.readLine()) != null){
int intValue = Integer.parseInt(line); //converts string into int
a[i] = intValue; // Store intValue into the array at index i
i++; // Increment i
}
return a;
}
note the additional variable i being used in this context to facilitate the incrementing index number being used to access the array. If you examine this method carefully, a input file longer than 25 elements would also throw ArrayIndexOutOfBoundsException due to the variable i becoming 25 (beyond the limits of the array). To fix, I'd suggest changing the loop structure to a for-loop (assuming your input array is of fixed size) as follows:
public static int[] processFile (String filename) throws IOException, FileNotFoundException{
BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));
String line;
int[] a = new int[25];
for(int i = 0; i < a.length; i++){
String line = inputReader.readLine(); // Move the readline code inside the loop
if(line == null){
// We hit EOF before we read 25 numbers, deal appropriately
}else{
a[i] = Integer.parseInt(line);
}
}
return a;
}
Note how the for loop integrates the iterator variable into one nice elegant line, keeping the rest of the code neat and readable.
Your mistake is in the line a[intValue]++;. You are telling Java to find the element at [intValue] and add 1 to it's current value. From your question, I understood that you want to put intValue as the array element.
Since you are using i as the iterator, to add the element simply use:
a[i] = intValue;
What you are doing here:
a[intValue]++;
is increasing the array position of the read value by one. If the number read is 2000 you are increasing a[2000]
you might want to do this
a[i]=intValue;

Counting Occurrences of a word using a input/output program in java

How would you find the most occurring words in a file that has five or more letters using an input/output program? This is a starter code that i have
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class FileIOtest {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File file = new File ("myfile.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String str =inputFile.nextLine();
System.out.println(str);
}
inputFile.close();
}
}
I would make a hashmap that holds a key-value pair between a word and a counter for the number of occurrences.
Map<String, Integer> myMap = new HashMap<String, Integer>();
You should split each line by white-space then iterate through the array of the split string. You can then check if the word is 5 or more characters and increment the counter in your hashmap
String str = inputFile.nextLine();
String[] parts = str.split(" ");
for(int x = 0; x < parts.length; x++)
{
String word = parts[x];
if(word.length() >= 5)
{
if(myMap.containsKey(word))
{
myMap.put(word, myMap.get(word) + 1);
}
else
{
myMap.put(word, new Integer(1));
}
}
}
Then at the very end you can get the HashMap's internal set with myMap.entrySet(). Then interate through that set to find the first, second, third, ect most common or least common words.

Need to put each string from a text file into an array [duplicate]

This question already has answers here:
Converting a sentence string to a string array of words in Java
(18 answers)
Closed 9 years ago.
I'm Trying to create a code that takes a text file and puts it in alphabetical order. To do this I was trying to read the file and the add each word into an array. I have an idea of how to go about doing this but don't know exactly. Here is what I have so far:
import java.io.*;
import java.util.Scanner;
public class assignment4 {
public static void main(String[] args) throws IOException {
if (args.length == 1){
createArray(args[0]);
System.exit(0);
}
}
public static String createArray(String fileName) {
File testFile = new File(fileName);
Scanner inputFile = new Scanner(testFile);
if (!testFile.exists()){
System.out.println("File Doesn't Exist");
System.exit(0);
}
String[] words;
while(inputFile.hasNext()){
for (int i=0;i<inputFile.length();i++){
words[i] = inputFile.nextLine();
}
}
return words[0];
}
}
I know the majority is probably completely wrong but I'm so confused been working on this for 4 hours now...
words[i] = inputFile.nextLine();
Here you are trying to store the next line from the input file into the index i of the words array. You have not declared or assigned a value to i, so Java won't know what you're trying to do.
With standard arrays, you must assign them an initial array value consisting of an explicit number of "slots" (indexes). With a Scanner, you could count the number of lines by reading them all and discarding the values. Once you have this counter, you can initialise the String[] with the appropriate size. Finally, you can read them all again and storing them into the array.
int counter = 0;
while (inputFile.hasNext()) {
inputFile.nextLine();
counter++;
}
inputFile = new Scanner(testFile); //to get to the beginning of the file
String[] words = new String[counter];
for (int i = 0; i < counter; i++) {
words[i] = inputFile.nextLine();
}
This is very bad practice; reading the whole file merely to find its length is an overkill, and a waste of resources.
Therefore, it would be much better to use a collection type that automatically expands as you put elements into it, such as an ArrayList.
ArrayList<String> lines = new ArrayList<String>();
while (inputFile.hasNext()) {
lines.add(inputFile.nextLine());
}
But it's likely that you're assignment requires you to use both Scanner and a standard String[]. In that case, you could change the size of the String[] manually:
String[] words = new String[0];
while (inputFile.hasNext()) {
words = Arrays.copyOf(words, words.length + 1);
words[words.length - 1] = inputFile.nextLine();
}
or
String[] words = new String[0];
while (inputFile.hasNext()) {
String temp = new String[words.length + 1];
System.arraycopy(words, 0, temp, 0, words.length);
temp[temp.length - 1] = inputFile.nextLine();
words = temp;
}
ArrayList words = new ArrayList();
while (inputFile.hasNextLine()){
String word = inputFile.getNextLine();
words.add(word);
}
Since you don't know how big this is, you should use an arrayList. You can then sort alphabetically or whatever you need.

Categories

Resources