Java mapping issue - java

Basically the program is supposed to search through a text file and find the amount of occurrences of different words and store them in an array and then display the word and the amount of times to the user. I tried using the map class but that was not successful due to the fact that it won't display the results. So I was wondering if anyone knows any other ways I could fix this file:
public class WordStats {
public static void main(String[] args) {
File textFile = new File("words.txt");
FileReader in;
BufferedReader readFile;
char charInFile;
String newWord = "";
String map=new String();
String existingMap=new String();
int wordIndex, index = 0;
ArrayList wordList = new ArrayList();
/* navigating the file */
try{
in = new FileReader(textFile);
readFile = new BufferedReader(in);
do{
charInFile = (char)readFile.read();
if(charInFile >= 'a' && charInFile <= 'z'){
while(charInFile >= 'a' && charInFile <= 'z'){
newWord += charInFile;
charInFile = (char)readFile.read();
}//end of while
wordIndex = wordList.indexOf(map);
if(wordIndex > -1){
existingMap = (String) wordList.get(wordIndex);
//existingMap.addOccurrence();
wordList.set(wordIndex, existingMap);
} else {
index = 0;
}
if(wordList.size() > 0){
do{
existingMap = (String) wordList.get(index);
index += 1;
}while(existingMap.compareTo(map) <= 0 && index <
wordList.size());
wordList.add(index-1, map);
}else{
wordList.add(map);
}
}//end of if
newWord = "";
}while(charInFile != (char)-1);
System.out.println("Word\t\tOccurrences");
for(Object Word : wordList){
System.out.println(Word);
}
readFile.close();
in.close();
}catch(FileNotFoundException e){
System.out.println("file could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
}catch(IOException e){
System.out.println("problem reading the file.");
System.err.println("IOException: " + e.getMessage());
}
}
}

Related

reading and writing files java

I have a float array which I stored in it some values from user input.
I have 2 methods one that saves the values stored in the array to a text file each value on a line and the second method rereads the values again and stores them in the array. for example, the user input was 1,2,3,4 I save them to a text file and then I read the same txt file now my array should display 8 elements 1,2,3,4,1,2,3,4.
the problem I'm having is that when I store these elements on the txt file it's storing them and adding like 100 zeros under them and when I'm calling the second method to reread these elements from the file it reads the zeros so when I'm displaying the elements in my array it's displaying 0,0,0,0 when it should display 1,2,3,4,1,2,3,4.
what might be causing me this problem?
public void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file dont exist");
e.printStackTrace();
}
}
public void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
You may check why the array is populated properly using additional println statement. In your version each element of array is populated with the same element read from the file. If you remove the inner loop, array will be populated properly.
int i=0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
System.out.println((i) + "::"+numbers[i]);
i++;
}
Zeros are being added because you're saving numbers as float. If you store an integer 3 in a float variable it will be converted to a float equivalent which is 3.0
Also you don't need two loops here,
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
You can instead do following,
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
Following is a fully functional program of what you desire,
import java.util.Scanner;
import java.io.*;
public class Hello {
public static float[] numbers = {1,2,3,4,1,2,3,4};
public static void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file doesn't exist");
e.printStackTrace();
}
}
public static void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
for(int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
saveValuesToFile(scanner);
readFromFile(scanner);
}
}

I need to print all unique words in an array of strings but not sure how

so the full program reads a story from a file and stores each word in an array of strings. After the story is read, I need to print all unique words in the story but I don't know how. Here is what I have
import java.util.*;
import csci1140.*;
import java.io.*;
public class Story{
public static final void main(String[] args){
String[] storyArray = new String[28203];
String fileName = "MultiLineStory.txt";
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(fileName));
}catch(FileNotFoundException fnfe){
System.out.println("Unable to find file: " + fileName);
}
try{
String input = null;
for(int i = 0; i < storyArray.length; i++){
if((input = reader.readLine()) != null){
String fill = input;
storyArray[i] = fill;
}
// System.out.print(storyArray[i] + " ");
}
} catch(IOException ioe){
ioe.printStackTrace(System.err);
} finally {
try{
reader.close();
}catch(Exception e){}
}
long start = System.nanoTime();
Arrays.sort(storyArray);
long end = System.nanoTime();
System.out.println("\n\nArrays.sort took " +((end - start)/1E9) + " Sec");
distinctValues(storyArray);
}
public static boolean distinctValues(String[] array){
int count = 0;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] == array[i + 1]) {
count++;
return true;
}
}
System.out.println(count);
return false;
}
}
You can use a HashSet<String> and put all elements of the array into it. Then just print them out one by one.
String[] allWordsArray = ...;
HashSet<String> uniqueWordsSet = new HashSet<>(Arrays.asList(allWordsArray));
for (String word : uniqueWordsSet)
{
System.out.println(word);
}
Try this:
package com;
import java.util.*;
import java.io.*;
/*to print unique words which are not repeated*/
public class UniqueWords {
public static final void main(String[] args){
ArrayList<String> allWords = new ArrayList<String>();
Map<String, Integer> map = new HashMap<String, Integer>();
String fileName = "C:\\TestFiles\\MultiLineStory.txt";
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(fileName));
String input = null;
if((input = reader.readLine()) != null){
String arr[] = input.split(" ");
allWords.addAll(Arrays.asList(arr));
}
System.out.println(allWords.size());
}catch(FileNotFoundException fnfe){
System.out.println("Unable to find file: " + fileName);
} catch(IOException ioe){
ioe.printStackTrace(System.err);
} finally {
try{
reader.close();
}catch(Exception e){}
}
for(String word : allWords)
{
if(!map.containsKey(word))
map.put(word, 1);
else
map.put(word, map.get(word)+1);
}
Set<String> keySet = map.keySet();
for(String key : keySet)
if(map.get(key)==1)
System.out.println(key);
}
}

How to count number occurrences of a word in a file using BufferedReader in Java

the task is to find number of occurrences of a particular word in a file
that person wrote herself.
public void reader() {
BufferedReader myR = myReader("enter the name of a file: ");
int count = 0;
String substring = readLine("enter the string to count for entry: ");
try {
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.contains(substring)){
count++;
}
}
}
myR.close();
} catch (IOException e) {
throw new ErrorException(e);
}
println("number of words is: " + count);
}
private BufferedReader myReader(String prompt) {
BufferedReader rd = null;
while (rd == null) {
try {
String name = readLine(prompt);
rd = new BufferedReader(new FileReader(name));
} catch (FileNotFoundException e) {
println("wrong file entered");
// e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return rd;
}
So the problem is that i can't figure out what to do if in my text file number of word i was checking is 4, but the code prints 671
the problem lies in this loop:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.contains(substring)){
count++;
}
}
}
now suppose your bufferedReader reads a line "hie i am user".
the size of this string is 13 so string.length(); would return 13.
that means you would be checking the same line for 13 iterations for your match.
So, suppose if you are looking for a match say "user" then checking for "user" on the same line for 13 times would make your count go up to 13.
you can replace the above code with this code:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
String[] slist = s.split(" ");
for(int j=0; j<slist.length(); j++){
if(slist[j].contains(substring)){
count++;
}
}
}
ohh!! you should have mentioned that you wanna do it without using an array.
this snippet should help you:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.equals(" ")){
String temp = s.substring(j+1, s.length());
String word = temp.substring(0,temp.indexOf(" ")-1);
if(temp.equalsIgnoringCases(word)){
count++;
}
}
}
}
now what i am doing here is first of all i am looking for a space in the whole string and upon finding one, I am extracting a substring starting from the index next to the index of space to the end of the string.
Now from this extracted substring, I am further extracting a substring from index zero up till the first space. this string is essentially a word suitable for comparison.

Made a wc program in Java, but it will not count end of line character

So I have pretty much completed (I think) my wc program in Java, that takes a filename from a user input (even multiple), and counts the lines, words, bytes (number of characters) from the file. There were 2 files provided for testing purposes, and they are in a .dat format, being readable from dos/linux command lines. Everything is working properly except for the count when there are \n or \r\n characters at the end of line. It will not count these. Please help?
import java.io.*;
import java.util.regex.Pattern;
public class Prog03 {
private static int totalWords = 0, currentWords = 0;
private static int totalLines =0, currentLines = 0;
private static int totalBytes = 0, currentBytes = 0;
public static void main(String[] args) {
System.out.println("This program determines the quantity of lines, words, and bytes\n" +
"in a file or files that you specify.\n" +
"\nPlease enter one or more file names, comma-separated: ");
getFileName();
System.out.println();
} // End of main method.
public static void countSingle (String fileName, BufferedReader in) {
try {
String line;
String[] words;
//int totalWords = 0;
int totalWords1 = 0;
int lines = 0;
int chars = 0;
while ((line = in.readLine()) != null) {
lines++;
currentLines = lines;
chars += line.length();
currentBytes = chars;
words = line.split(" ");
totalWords1 += countWords(line);
currentWords = totalWords1;
} // End of while loop.
System.out.println(currentLines + "\t\t" + currentWords + "\t\t" + currentBytes + "\t\t"
+ fileName);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void countMultiple(String fileName, BufferedReader in) {
try {
String line;
String[] words;
int totalWords1 = 0;
int lines = 0;
int chars = 0;
while ((line = in.readLine()) != null) {
lines++;
currentLines = lines;
chars += line.length();
currentBytes = chars;
words = line.split(" ");
totalWords1 += countWords(line);
currentWords = totalWords1;
} // End of while loop.
totalLines += currentLines;
totalBytes += currentBytes;
totalWords += totalWords1;
} catch (Exception ex) {
ex.printStackTrace();
}
} // End of method count().
private static long countWords(String line) {
long numWords = 0;
int index = 0;
boolean prevWhitespace = true;
while (index < line.length()) {
char c = line.charAt(index++);
boolean currWhitespace = Character.isWhitespace(c);
if (prevWhitespace && !currWhitespace) {
numWords++;
}
prevWhitespace = currWhitespace;
}
return numWords;
} // End of method countWords().
private static void getFileName() {
BufferedReader in ;
try {
in = new BufferedReader(new InputStreamReader(System.in));
String fileName = in.readLine();
String [] files = fileName.split(", ");
System.out.println("Lines\t\tWords\t\tBytes" +
"\n--------\t--------\t--------");
for (int i = 0; i < files.length; i++) {
FileReader fileReader = new FileReader(files[i]);
in = new BufferedReader(fileReader);
if (files.length == 1) {
countSingle(files[0], in);
in.close();
}
else {
countMultiple(files[i], in);
System.out.println(currentLines + "\t\t" +
currentWords + "\t\t" + currentBytes + "\t\t"
+ files[i]);
in.close();
}
}
if (files.length > 1) {
System.out.println("----------------------------------------" +
"\n" + totalLines + "\t\t" + totalWords + "\t\t" + totalBytes + "\t\tTotals");
}
}
catch (FileNotFoundException ioe) {
System.out.println("The specified file was not found. Please recheck "
+ "the spelling and try again.");
ioe.printStackTrace();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
} // End of class
that is the entire program, if anyone helping should need to see anything, however this is where I count the length of each string in a line (and I assumed that the eol characters would be part of this count, but they aren't.)
public static void countMultiple(String fileName, BufferedReader in) {
try {
String line;
String[] words;
int totalWords1 = 0;
int lines = 0;
int chars = 0;
while ((line = in.readLine()) != null) {
lines++;
currentLines = lines;
**chars += line.length();**
currentBytes = chars;
words = line.split(" ");
totalWords1 += countWords(line);
currentWords = totalWords1;
} // End of while loop.
totalLines += currentLines;
totalBytes += currentBytes;
totalWords += totalWords1;
} catch (Exception ex) {
ex.printStackTrace();
}
}
BufferedReader always ignores new line or line break character. There is no way to do this using readLine().
You can use read() method instead. But in that case you have to read each character individually.
just a comment, to split a line to words, it is not enough to split based on single space: line.split(" "); you will miss if there are multiple spaces or tabs between words. better to do split on any whitespace char line.split("\\s+");

Guess A word (Java)

Hello I have to create a program that lets the player guess a word. The code I have works fine but I have to write a condition that allows the player 7 tries, if the player does not guess the word on the 7th try he/she losses. I don't know how to write this condition. Here is my code:
package javaapplication5;
import java.io.*;
import java.lang.*;
import java.util.*;
public class NewClass2{
public static int ReadWordsFromFile(String[] words)
{
try
{
FileReader fr = new FileReader("Guess_words.txt");
BufferedReader br = new BufferedReader(fr);
int count = 0;
for (int i = 0; i <87; i++)
{
String s = br.readLine();
if (s == null)
break;
words[count++] = s;
}
fr.close();
return count;
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
return -1;
}
catch (IOException err)
{
System.out.println(err.getStackTrace());
return -1;
}
}
static public String ReadString()
{
try
{
String inpString = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
return reader.readLine();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
public static void main(String[] args)
{
System.out.println("Welcome to Guess a Word\n");
String[] words = new String[87];
int count = ReadWordsFromFile(words);
if (count < 0)
{
System.out.println("No words found in the file");
return;
}
if (words == null)
return; // Exception message was already shown
int x = (int)(Math.random() * 87);
int guessX = (x % count);
String secretWord = words[guessX];
int numChars = secretWord.length();
System.out.print("Your secret word is: ");
for(int i = 0; i < numChars; i++)
System.out.print("*");
System.out.println();
boolean bGuessedCorrectly = false;
System.out.println("Guess now (To stop the program, enter #) : ");
while (true)
{
String choice = ReadString();
if (choice.startsWith("#"))
break;
if (choice.compareTo(secretWord) == 0)
{
bGuessedCorrectly = true;
break;
}
for (int i = 0; i < numChars; i++)
{
if (i < secretWord.length() &&
i < choice.length())
{
if (secretWord.charAt(i) == choice.charAt(i))
System.out.print(choice.charAt(i));
else
System.out.print("*");
}
else
System.out.print("*");
}
System.out.println();
}
if (bGuessedCorrectly == false)
System.out.println("Unfortunately you did not guess it correctly. The secret word is: " + secretWord);
else
System.out.println("Congrats! You have guessed it correctly");
}
}
Why not simply change your loop from this:
while (true) {
}
To this:
for (int nrOfGuesses = 0; nrOfGuesses < 7; nrOfGuesses++) {
// do stuff
}

Categories