input string problem - java

System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan2.nextLine();
String[] array2 = word2.split(" ");
for (int b = 0; b < array2.length; b++) {
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++;
} catch (IOException e) {
System.out.println("File not found.");
}
}
System.out.println("This file contain the term " + numofDoc);
}
}
}
this is my code for calculating number of documents containing a specific term. For example :
assume i have 10 million text file and string COW appears in one thousand of these. I am looking for the total one thousand documents containing the COW string.
My program currently only can process one string input.
The output of my program is :
COW
The files containing this term is 1000.
The problem i facing now is when i input 3 strings, It cannot process 3 strings. For example :
COW IS GOOD
The files containing this term is 0.
The files containing this term is 0.
The files containing this term is 0.
I have been trying whole day but i cant see where is my mistake. Mind pointing my mistakes ?

According to your code, you do a loop 3 times (array2.length) but you don't use the array2 at all, instead, you look for the string "COW IS GOOD" three times. you should change the line s2.next().equals(word2) to s2.next().equals(array2[b])

The problem lies here:
if (s2.next().equals(word2))
if word2 = "I love you" and you're doing an equals(), s2.next() must contain the word I love you.
One way to solve this.
String[] words = word2.split(" ");
for (String word: words) {
if (s2.next().equals(word)) {
matchedWord++;
}
}

Related

How to let the user pick certain positions in an array and write it to a file

I have been stuck for some time now. In my code, I want to read all of the names I have from a separate file, and I want to allow the user to select how many names they want to save to a new separate file and allow them to select which names they want to save to the file (by selecting the number in-front of the names printed to the screen).
I am not sure on how I would allow the user to select certain positions in the array "names" to print to a new file. My idea was to use the array "select" and check what number was in that array (eg select[0] = 1) and print out number[1].
Any help would be much appreciated, thankyou!
public class Main {
public static void main(String[] args) throws IOException {
BufferedWriter writefile;
BufferedReader readfile;
Scanner scan = new Scanner(System.in);
readfile = new BufferedReader(new FileReader("names.txt"));
writefile = new BufferedWriter(new FileWriter("nameChoices.txt"));
String names[] = new String[10];
System.out.println("Here are the list of names:");
System.out.println();
for (int i = 0; i < 10; i++) {
names[i] = readfile.readLine();
System.out.println(i + ". " + names[i]);
}
System.out.println();
System.out.println("Please enter the number of names you want to select:");
int choice = scan.nextInt();
System.out.println("Enter the number infront of the names you want to select: ");
int select[] = new int[choice];
for (int j = 0; j < choice; j++) {
select[j] = scan.nextInt();
}
}
}
Your Question: "I am not sure on how I would allow the user to select certain positions in the array "names" to print to a new file."
There is nothing wrong with the way you have already opted to do this other than perhaps letting the User know what selection they happen to be currently on and trapping for invalid entries such as values too high or too low and of course alpha characters where numerical characters are required. Without taking care of this business you leave things open to specific Error Exceptions. When asking the User for input a good solution would be for you to take care of what can go wrong and if it does, allow the User to re-enter the required data.
The biggest problem you have is that you have no mechanism in place to write the desired data to file. You've started by declaring a BufferedWriter object but you have yet to implement it. This would of course entail iterating through the select array which ultimately each element holds the index of the names desired to save to file. Simply iterate through the select array and write each name to file:
for (int i = 0; i < select.length; i++) {
writefile.write(name[select[i]] + System.lineSeparator());
writefile.flush();
}
// Close the file when all writing is done.
writefile.close();
With what is discussed above you might have a solution that would look something like this:
try {
BufferedWriter writefile = new BufferedWriter(new FileWriter("nameChoices.txt"));
BufferedReader readfile = new BufferedReader(new FileReader("names.txt"));
Scanner scan = new Scanner(System.in);
String allNames = "", fileLine = "";
while((fileLine = readfile.readLine()) != null) {
// Using a 'Terary Operator' to fill the allNames variable
// with a comma delimited string of all the names in file. It
// doesn't matter how many names are in file.
allNames+= (allNames.equals("")) ? fileLine : "," + fileLine;
}
// Split the string in allNames to the names array.
String names[] = allNames.split(",");
// Display the names in console:
// Use the System.out.format() method
// to create a columnar display.
System.out.println("Here are the list of names:");
for (int i = 0; i < names.length; i++) {
// Use the modulus operator to ensure 4 columns
if (i % 4 == 0){
// Print a new line
System.out.print("\n");
}
System.out.format("%-15s", (i+1) + ". " + names[i]);
}
readfile.close(); // Close the reader. Don't need to leave it open.
System.out.println();
// Get the number of names the User wants to save...
int choice = 0;
while (choice == 0) {
System.out.println("\nPlease enter the number of names you want to select:");
try {
choice = scan.nextInt();
}
catch (InputMismatchException ex) {
System.err.println("Invalid Entry! Numerical value Only!\n");
scan.nextLine(); // Clear the scanner buffer
choice = 0;
}
}
// Get the actual names the User wants to save...
System.out.println();
int j = 0;
int select[] = new int[choice];
System.out.println("Enter the numbers in front of the names you want to select: ");
while (j < choice) {
System.out.println("Enter the number for name #" + (j+1) + ": ");
try {
int index = scan.nextInt();
if (index < 1 || index > names.length) {
throw new InputMismatchException();
}
select[j] = index;
j++;
}
catch (InputMismatchException ex) {
System.err.println("Invalid Entry! Numerical value Only (1 to " +
names.length + ")!\n");
scan.nextLine(); // Clear the scanner buffer
}
}
//Write choices to file and Console...
System.out.print("\nSaving Names: ");
for (int i = 0; i < select.length; i++) {
String save = names[select[i]-1] ;
System.out.print(save + "\t");
writefile.write(save + System.lineSeparator());
writefile.flush();
}
writefile.close(); // close the writer
System.out.println("\nDONE! File Created!");
}
catch (IOException ex) { ex.printStackTrace(); }
In this example invalid entries are taken care of and the User is given the chance to enter valid data.

Printing An External File's Contents

below is my code for a homework assignment where I need to read the contents of an external file and determine the number of words within it, number of 3-letter words, and percentage of total. I've got that part down just fine, but I also have to print the external file's contents prior to displaying the above information. Below is my current code:
public class Prog512h
{
public static void main( String[] args)
{
int countsOf3 = 0;
int countWords = 0;
DecimalFormat round = new DecimalFormat("##.00"); // will round final value to two decimal places
Scanner poem = null;
try
{
poem = new Scanner (new File("prog512h.dat.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!"); // returns error if file is not found
System.exit (0);
}
while (poem.hasNext())
{
String s = poem.nextLine();
String[] words = s.split(" ");
countWords += words.length;
for (int i = 0; i < words.length; i++)
{
countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words
}
}
while(poem.hasNext())
{
System.out.println(poem.nextLine());
}
System.out.println();
System.out.println("Number of words: " + countWords);
System.out.println("Number of 3-letter words: " + countsOf3);
System.out.println("Percentage of total: " + round.format((double)((double)countsOf3 / (double)countWords) * 100.0)); // converts value to double and calculates percentage by dividing from total number of words
}
}
The statement
while(poem.hasNext())
{
System.out.println(poem.nextLine());
}
is supposed to print the external file's contents. However, it doesn't. When I try moving it before my prior while loop, it prints, but screws up my printed values for the # of words, 3-letter words, percentage, etc. I'm not really sure what the issue is here. Could someone provide some assistance?
Thank you in advance.
Your scanner is trying to reread the file but it is at the bottom so there are no more lines to read. You have two options:
Option 1
Create a new Scanner object for the same file (to start at the beginning again) and then call your while loop on that file (works, but not a great design).
Scanner poem2 = null;
try
{
poem2 = new Scanner (new File("prog512h.dat.txt"));
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!"); // returns error if file is not found
System.exit (0);
}
while(poem2.hasNext())
{
System.out.println(poem2.nextLine());
}
Option 2
A better option would be to display each line as you read it in. This can be accomplished by adding an extra line to the already existent while loop:
while (poem.hasNext())
{
String s = poem.nextLine();
System.out.println(s); // <<< Display each line as you process it
String[] words = s.split(" ");
countWords += words.length;
for (int i = 0; i < words.length; i++)
{
countsOf3 += words[i].length() == 3 ? 1 : 0; // checks for 3-letter words
}
}
This only requires one Scanner object and only requires one read-through of the file which is much more efficient.

how to store a text file into an array and count how many words are in it

I was given a homework in which I need to count the number of words in a file and output how many words are the same. Like "a" in the whole text maybe it was repeated 350 times. I hope you get my point.
Now, im trying to do some tests and created a file("test.txt") containing:
Im a good boy
Hello World
A happy world it is
What I'm trying to do is storing it into an array to be able to count the words in the file. But I'm having a hard time. This is what i got so far.
void readFile() {
System.out.println("Gi navnet til filen: ");
String filNavn = sc.next();
File k = new File(filNavn);
try {
Scanner sc2 = new Scanner(k);
while (sc2.hasNextLine()) {
String line = sc2.nextLine();
String[] m = line.split(" ");
String x = m[0];
System.out.println(x);
}
} catch (FileNotFoundException e) {
System.out.print("mmm");
}
}
but this only outputs the first words on the line.
What I would like to see is the same as the text file. But stored in an array. How can I do it?
Im a good boy
Hello World
A happy world it is
This will only print out the first word because of this
String[] m = line.split(" ");
String x = m[0];
System.out.println(x);
Here you are only assigning the first word in the array (created by your split) to the variable x and then printing only that word.
To print all the words you will need to loop the array like so
for(int i = 0; i < m.length; i++)
{
System.out.println(m[i]);
}
And to print the same as the file you could use System.out.print(). Note you will need to put the spaces back in and also account for the new lines. Below is one approach:
for(int i = 0; i < m.length; i++)
{
if(i == m.length - 1)
System.out.print(m[i] + "\n");
else
System.out.print(m[i] + " ");
}
Since your post didn't say you HAD to do it in Java (although I am guessing that is the case), I offer this:
perl -e 'while(<STDIN>) { map { $w->{lc($_)}++; } split("\\s", $_); } map { print "$_ $w->{$_}\n"; } keys %{$w} ;' < test.txt

java read input from file with multiple data types of varying lengths

I'm trying to read from a file containing names and doubles, this would be easy if it was first name, last name then the doubles, but some of the lines have a middle initial and some have just one name.
Like this:
Hancock John 40.00 9.75
Light Karen L 40.00 9.60
Bob 12.02 42.90
and so on
I'm putting the names into a string array and the numbers into a 2d array.
So how would I separate those data types?
EDIT:
I was trying this at first
import java.io.*;
import java.text.*;
import java.util.*;
public class JEdwards11
{
public static void main(String[] args) throws Exception
{ PrintWriter outFile = new PrintWriter("H:/Java/program11.out");
String filename = "H:/Java/program11.dat", line, fullname;
StringTokenizer st;
Scanner inFile = new Scanner(new FileReader(filename));
int ctr = 0, i = 0, k = 0;
String [] names = new String [30];//print vertically
double [][] money = new double [7][30];//short across, long down
//hours worked, hourly rate, gross pay, net pay, fed, state, union
//while(inFile.hasNext())
for(i=0; i< names.length; i++)
{
if(inFile.hasNextDouble())
{money[1][i] = inFile.nextDouble();
money[2][i] = inFile.nextDouble();}
else
names[i] = inFile.next();
}
/*while(inFile.hasNext())
{line = inFile.nextLine();
st = new StringTokenizer(line);
names[i]=st.nextString;
money[1][i] = st.nextDouble();
money[2][i] = st.nextDouble();*/
for(i=0;i<names.length;i++)
for(i=0; i<names.length; i++)
System.out.println("name = " + names[i] +" money1 = "+money[1][i] +" money2= "+money[2][i]);
inFile.close();
outFile.close();
}
}
which did not work at all. Since then I've searching Google and re-reading my java book. Sorry for the formatting, it's not being cut/paste friendly and last time I hit enter it posted before I was ready :(
You may have followed another approach. Anyway I give you one easy trick to solve it with Scanner, just add tokens to a buffer until digits are encountered, then assign it to the name array.
Again, your if-else block is erroneous since per iteration either if-part or the else-part will be executed. Try something like this, it will definitely solve your problem :
for (i = 0; i < names.length; i++) {
StringBuffer sbr = new StringBuffer();
while (inFile.hasNext("[a-zA-Z]+")) {
sbr.append(inFile.next() + " ");
}
names[i] = sbr.toString().trim();
if (inFile.hasNextDouble()) {
money[1][i] = inFile.nextDouble();
money[2][i] = inFile.nextDouble();
}
}
Are you familiar with Scanner?
http://www.tutorialspoint.com/java/util/java_util_scanner.htm
There's a link, or just google Java.Util.Scanner.
I would init a Java.Util.Scanner with the file text, then use calls to hasNextDouble() to determine if next token is a double. If so, scan it with nextDouble, otherwise treat the next token as part of a name.
//psuedo code
Scanner s; // init with file
while ( s.hasNext() )
{
if ( s.hasNextDouble() )
{
double d = s.nextDouble();
// add to array
}
else
{
String name = s.next();
// add to names
}
}

counting the number of documents containing a specific term

File folder2 = new File("C:\\Users\\user\\fypworkspace\\TextRenderer");
File[] listOfFiles2 = folder.listFiles();
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan.nextLine();
String [] array2 = word2.split(" ");
{
for (int i=0; i < listOfFiles.length; i++)
{
if ((listOfFiles2[i].getName().endsWith(".txt")))
{
try
{
BufferedReader in= new BufferedReader(new FileReader(listOfFiles2[i].getName()));
int numDoc = 0;
Scanner s2 = new Scanner(listOfFiles2[i].getName());
{
while (s2.hasNext())
{
if (s2.next().equals(word2)) numDoc++;
}
System.out.println("The number of document containing the term is " + numDoc);
}
in.close();
} catch (IOException e) {
}
This is my code for counting the number of documents that contain a specific term.
Every time the program finds a specific term inside the document, it will increment numDoc counter.
This code does not do anything, however. What am I doing wrong?
Add System.out.println() throughout your code to output important information for debugging.
Not directly related but you can use a enhance for loop to loop through the files. See: http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Your System.out.println for your total is inside your loop and it should be outside after you have finished looping through all the documents.
(And maybe the most important) You are not handling your IOException. At the least printout a stack trace or the message from the exception.

Categories