the counter does not working - java

this code i have been doing suppose to add a counter everytime the code found a term in a file. The counter represents the number of documents containing the term.
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan.nextLine();
String[] array2 = word2.split(" ");
for (int b = 0; b < array.length; b++) {
for (int i = 0; i < filename; i++) {
try {
BufferedReader in = new BufferedReader(new FileReader(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
+ i + ".txt"));
int numDoc = 0;
int numofDoc = 0;
Scanner s2 = new Scanner(in);
{
while (s2.hasNext()) {
if (s2.next().equals(word2))
numDoc++;
}
}
if (numDoc > 0)
numofDoc++;
System.out.println("File containing the term is "
+ numofDoc);
} catch (IOException e) {
System.out.println("File not found.");
}
The output is :
Please enter the required word :
the
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File not found
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
I would like the output to display the number of file containing the term is 10.
Mind to point out my mistake ? thanks..

Indent your code properly (under Eclipse, CTRL + SHIFT + F will do it for you)
Give sensible and explicit names to your variables. numDoc and numOfDoc are too close to avoid mistakes
You are outputing the counter in the inner loop, try to get your System.out.println("File containing the term is " + numofDoc); out of the second for loop (this can easily be spotted if you indent your code properly). Also check that you are outputting the right variable.
Now that you print the result in the proper place, int numofDoc = 0; shall also be outside the second for loop.
Additionally, you are using String.equals to check if the current line of the file contains the required text. Maybe you want to look for the documentation of String.contains

I guess that numDoc represents the number of occurences in the file and numofDoc reprents the number of files.
The problem is that the variable int numofDoc = 0 is set in the for loop. So for every new file the counter is reset.

Set int numDoc = 0; before the two loops.
So you're setting back the value to 0 every time the loop is executed.

declare int numDoc = 0; int numofDoc = 0; outside for loop.
whenever executing to for loop, they initialized & then incremented to 1. That's why you getting all time 1.

I think you want to do this
public static void main(String[] args)
{
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan.nextLine();
String[] array2 = word2.split(" ");
for ( int b = 0; b < array.length; b++ )
{
**//Declare before the loop**
int numofDoc = 0;
for ( int i = 0; i < filename; i++ )
{
try
{
BufferedReader in = new BufferedReader(new FileReader(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + i + ".txt"));
int matchedWord = 0;
Scanner s2 = new Scanner(in);
{
while ( s2.hasNext() )
{
if ( s2.next().equals(word2) )
matchedWord++;
}
}
if ( matchedWord > 0 )
numofDoc++;
System.out.println("File containing the term is " + numofDoc);
}
catch ( IOException e )
{
System.out.println("File not found.");
}
}
}
}

Related

Best way to read CSV file and store (array, 2darray?) and print to screen in tabular format?

The thing i'm hoping to do is read a csv file with 6 rows and 6 columns in it using Java. I then need to print out each row and allow the user to select 1 option. Here is what I have, I know my code chooses 1 and prints it, but I don't know how to change it from printing one random row, to printing all 6 rows. Probably in an ArrayList or 2dArray?
package theContest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;
public class theContest {
// The main() method
public static void main(String[] args) throws FileNotFoundException {
//
String fileName = "contest.csv";
File file = new File(fileName);
if (!file.isFile()) {
System.err.println("Cannot open file: " + fileName + ".");
System.exit(0);
}
//
int numContest = 0;
Scanner input = new Scanner(file);
while (input.hasNext()) {
input.nextLine();
numContest++;
}
input.close();
System.out.println("Total of " + numContest + " contestants.");
//
int winner = 0;
Random random = new Random();
winner = random.nextInt(numContest) + 1;
System.out.println("The winner is contestant number " + winner + ".");
//
String winnerDetails = "";
input = new Scanner(file);
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
input.close();
System.out.println("Winner is: " + winnerDetails);
//
String id = "";
String name = "";
String seats = "";
String trans = "";
String rate = "";
String price = "";
input = new Scanner(winnerDetails);
input.useDelimiter(",");
id = input.next();
name = input.next();
seats = input.next();
trans = input.next();
rate = input.next();
price = input.next();
input.close();
System.out.println("Details are:");
System.out.printf("%-5s : %s\n", "ID", id);
System.out.printf("%-5s : %s\n", "Name", name);
System.out.printf("%-5s : %s\n", "Seating", seats};
System.out.printf("%-5s : %s\n", "Transfer", trans};
System.out.printf("%-5s : %s\n", "Rate", rate};
System.out.printf("%-5s : %s\n", "Price", price};
}
}
Here:
for (int lineCount = 0; lineCount < winner; lineCount++) {
winnerDetails = input.nextLine();
}
Your file has N rows. The above code iterates all lines, and stores the result in a single variable. In each iteration, you overwrite what you put there before. So, what your code does is: it reads N lines, and throws away everything prior the last row.
In other words: if you have 6 lines, and you want to print all of them ... then that all your processing needs to be "part" of a loop, too.
For example, you could turn winnerDetails into an array of String, and then put each line in its own slot. Then you loop over the array, and print each slot.
And as you already know about ArrayList, best use that then. That also means: you need to read the file only once. Open the file, read each line, and push that into an ArrayList. Afterwards, you can do whatever you want with that list.
And note: that is actually the point you should start with. Dont solve your whole problem at once. Slice it into smaller parts. Like: reading data from CSV ... has nothing to do with later processing the lines and printing those. You can write code that just takes an ArrayList, processes those and prints stuff. Which you can ... test on its own, as you can hardcode such lists in your code.

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();
}

java program read and print to text file using Scanner

I am trying to read a text file, and then display the output in another file.
I can only read using Scanner.
input.txt
3005045 7
3245436 0
7543536 3
8684383 -1
output.txt should be like
ID Number of Bags Total Cost
** ************** **********
customer pays 20.50 per bag if the bag is 4 or less.
and pays 15.50 per bag if the bag greater than 4.
but if it's 0 or negative number this message should appeared "Error : Wrong Number of Bags"
I did this program, but it works only once(reads one line only)
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Bags {
public static void main(String []args) throws IOException {
FileInputStream fileinput = new FileInputStream("input.txt");
FileOutputStream fileoutput = new FileOutputStream("output.txt");
Scanner infile = new Scanner(fileinput);
PrintWriter pw = new PrintWriter(fileoutput);
double total = 0, line = 0;
int bags = 0, ID = 0, count = 0;
pw.println("ID\t\tNumber of Bags\t\t\tTotal Cost");
for(int i = bags; i >= 0; i++, count++){
ID = infile.nextInt();
i = infile.nextInt();
if (i <= 0){
pw.println(ID + "\tError: Wrong Number of Bags\t\t\t");
break;
}
else if (i <= 4){
total = (80.50)*i;
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
break;
}
else {
total = ((80.50)*4)+((75.50)*(i-4));
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
break;
}
}
infile.close();
pw.close();
}
}
You don't need that for loop over there. Also, you want to read line by line. Here is quick fix of your code:
public class Bags {
public static void main(String[] args) throws IOException {
FileInputStream fileinput = new FileInputStream("input.txt");
FileOutputStream fileoutput = new FileOutputStream("output.txt");
Scanner infile = new Scanner(fileinput);
PrintWriter pw = new PrintWriter(fileoutput);
double total = 0, line = 0;
int bags = 0, ID = 0, count = 0;
pw.println("ID\t\tNumber of Bags\t\t\tTotal Cost");
while(infile.hasNext()){
ID = infile.nextInt();
int i = infile.nextInt();
if (i <= 0) {
pw.println(ID + "\n\t\tError: Wrong Number of Bags\t\t\t");
} else if (i <= 4) {
total = (80.50) * i;
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
} else {
total = ((80.50) * 4) + ((75.50) * (i - 4));
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
}
}
infile.close();
pw.close();
}
}
Output.txt
ID Number of Bags Total Cost
3005045 7 548.503245436
Error: Wrong Number of Bags
7543536 3 241.508684383
Error: Wrong Number of Bags
You should not use i to save "number of bags". See the line i = infile.nextInt();. Use another variable, then you should be fine. Also, you should keep reading until end of file, so you probably wouldn't be able to write a for (int i = 0; i < n; i++)-style of loop.
There is no surprise that loop can iterates only one time. In each case you have break.
Also in this case you shouldn't be using for loop, and especially not the way you are using it now. Just take a look at it, your loop would end only when this condition i >= 0 would be false, which means i would have to be negative, but even when i would become -1 like last number from your input it would still be incremented at the end of iteration thanks to i++ so you would end up with 0 >= 0 condition which is true, so loop would try to iterate again)
Instead use
while(scanner.hasNextInt())
This way you will make sure that you will read int from file only when there will be next one to read. Just use your predefined bugs variable instead of i.
Another thing is that you are not including line separators in your printf formats. Add %n at the end of each one of them, and don't use \t but specify space you want each number to hold like
pw.printf("%d %9d %40.2f%n",...);

Error: The local variable jars may not have been initialized

Further down it keeps saying the tow local variable cant be initialized when they are. Cant seem to find the problem
import java.io.*;
import java.util.Scanner; //Scanner method
public class Popcorn1 {
public static void main(String args[]) throws FileNotFoundException{
printHeader();
File file;
do {
Scanner in = new Scanner (System.in);
System.out.println("Enter the the file name");
String filename = in.next();
file = new File(filename);
} while(!file.exists());
FileReader inputFile = new FileReader (file);
Scanner inFile = new Scanner(inputFile);
System.out.println(" PopCorn Co-op");
System.out.println(" Production in Hundreds");
System.out.println(" of Pint Jars Per Acre");
System.out.println(" 1 2 3 4 5 6");
System.out.println("Farm Name ---|---|---|---|---|---|");
System.out.println();
// Printing out title and table header for reader to easily read data
String errorMSG = " ";
while (inFile.hasNextLine()) {
String inputLine = inFile.nextLine();
//System.out.print(inputLine);
int position;
String name;
int jars;
double acres;
position = inputLine.indexOf(','); //Get the Location of the comma to use as a delimiter
name = inputLine.substring(0,position); //Everything to the left of the comma is the farm name
System.out.printf("%-31s", name);
inputLine = inputLine.substring(position + 2,inputLine.length()); //rest of the string
Scanner line = new Scanner(inputLine);
if(line.hasNextDouble())
acres = line.nextDouble();
else
errorMSG += "There is missing data";
if(line.hasNextInt())
jars = line.nextInt();
else
errorMSG += "There is missing data";
int starsConversion =(int)(jars/acres/25); **<-------- problem is here**
for (int i = 1; i < starsConversion; i++) {
if( i == 20)
System.out.print("#");
else
System.out.print("*");
}
if (starsConversion < 20) {
for (int i = 1; i < (21 - starsConversion); i++) {
System.out.print(" ");
}
System.out.print("|");}
System.out.println(); //go to the next line
}
System.out.println(errorMSG);
}
}
There is an execution path where jars was never initialized, specifically, if line.hasNextInt() is false.
To use it, you must make sure jars is always initialized to something. You can initialize it to say 0 before the if.
What happens if if(line.hasNextInt()) is false on the first run?

Categories

Resources