I am trying to link two files together and have one count the amount of characters and have the other one give the answer to the character counter. The first file cant have the word that is being given to be displayed as well. How would I go about doing so?
File one
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
System.out.println("Line " + (answer + 1));
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("The specific Line is: " + text);
}
File two
public class countWords
{
public static void main(String[] args) {
String string = "nose";
int count = 0;
//Counts each character except space
string = string.replaceAll(" ", "");
count = string.length();
//Displays the total number of characters present in the given string
System.out.println("Total number of characters in a string: " + count);
}
}
Figured it out for the first file
import java.io.*;
import java.util.Random;
public class Main {
public static void main(String[] args) {
String text = "There isn't and exitsing output for that";
try {
FileReader readfile = new FileReader("resources/words.txt");
BufferedReader readbuffer = new BufferedReader(readfile);
Random rn = new Random();
int lines = 0;
while (readbuffer.readLine() != null) {lines++;}
int answer = rn.nextInt(lines);
readfile = new FileReader("resources/words.txt");
readbuffer = new BufferedReader(readfile);
for (int i = 0; i < answer; i++) {
readbuffer.readLine();
}
text = readbuffer.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
WordCounter wc = new WordCounter(text);
wc.removeSpaces();
wc.count();
int letters = wc.getCount();
System.out.println("The amount of characters is:" + letters);
}
}
Got the second file
public class WordCounter
{
private final String word;
private int count = 0;
public WordCounter(String word) {
this.word = word;
}
public void removeSpaces() {
word.replaceAll(" ", "");
}
public void count() {
count = word.length();
}
public int getCount() {
return count;
}
}
A folder contains number of text files like a.txt, b.txt, c.txt like that more than 30 files I need to search a particular string in the all files the output should come as follows:
a.txt contains your entered string
20
b.txt contains you entered string
30
And so on...
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter String");
String input = sc.nextLine();
double count = 0, countBuffer = 0, countLine = 0;
String lineNumber = ".txt";
File folder = new File("C://Users//Desktop//Santhosh.txt");
BufferedReader br;
String line = " ";
try {
br = new BufferedReader(new FileReader(folder));
try {
while ((line = br.readLine()) != null) {
countLine++;
//System.out.println(line);
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(input)) {
count++;
countBuffer++;
}
}
#santhosh I think you want to search a text in files and count the occurrence of word according to file here is the program that do this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class TextSearch {
File file;
FileReader reader;
BufferedReader buffReader;
String word;
Scanner scanner;
Map<String, Integer> counter = new TreeMap<String, Integer>();
public TextSearch() {
file = new File("D:\\Backup\\NP\\GN");// This Contain the 30 files
scanner = new Scanner(System.in);
System.out.println("Enter a word");
word = scanner.nextLine();
File[] listOfFiles = file.listFiles();
startSearch(listOfFiles);
Iterator<String> iterator = counter.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + " contain this word " + word + " " + counter.get(key) + "times");
}
}
public void startSearch(File[] list) {
for (int i = 0; i < list.length; i++) {
if (list[i].isFile()) {
try {
reader = new FileReader(list[i]);
buffReader = new BufferedReader(reader);
String line = "";
while ((line = buffReader.readLine()) != null) {
if (line.contains(word)) {
if (counter.containsKey(list[i].getName())) {
Integer count = counter.get(list[i].getName());
count++;
counter.put(list[i].getName(), count);
} else {
counter.put(list[i].getName(), 1);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]) {
new TextSearch();
}
}
public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
on hover over component 1 change the style
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadTemps{
public static void main(String[] args) throws IOException {
//taking the word to search from keyboard
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the word you want to search: ");
String input = keyboard.nextLine();
//counter for calculating how many times word wrote in line
int counter = 0;
//counter to find which line we are searching
int counterLine = 1;
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("C:\\KeyWestTemp.txt"));
// Original answer used LinkedList, but probably preferable to use
// ArrayList in most cases
// List<String> temps = new LinkedList<String>();
ArrayList<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
token1 = inFile1.nextLine();
//removing whitespeaces
token1.replaceAll("\\s+","");
//taking all the letters as String
for(int i = 0; i < token1.length(); i++) {
char c = token1.charAt(i);
String s = "" + c;
temps.add(s);
}
//adding a point to find line' end
temps.add("line");
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
//searching on array to find first letter of word
for (int i = 0; i < tempsArray.length; i++) {
String s = temps.get(i);
//if its the end of line time to print
if(s.equals("line")) {
System.out.println("Line" + counterLine + " : " + counter + " occurrence ");
counterLine++;
counter = 0;
}
//if the first letter found need to search rest of the letters
if(s.equalsIgnoreCase("" + input.charAt(0))) {
s = "";
try {
for(int j = i; j < i + input.length(); j++) {
String comp = temps.get(j);
if(comp.equalsIgnoreCase("" + input.charAt(j-i)))
s = s + comp;
}
} catch (IndexOutOfBoundsException e) {
}
//checks if found the word
if(s.equalsIgnoreCase(input))
counter++;
}
}
}
}
This is the code i got for searching char by char for wanted String.
Rather than using inFile1.next();, use inFile1.nextLine(), and don't bother wasting time using a token string.
while (inFile1.hasNext()) {
temps.add(inFile1.nextLine());
}
use BUFFERED READER , it read line by line
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String fullLine;
while ((line = br.readLine()) != null) {
}
}
After I input the number of letters I want the word for the computer to use for me to guess it, for example, I type 4, the program is terminated. I have spent some time debugging it but I cannot figure out the problem. I want the program to ask me to input a letter after inputting the length of the word, but it does not. instead, the program terminates after I input the number and I cannot type anything How can I get the program in my code to do what I typed in it?
It should look like this:
http://nifty.stanford.edu/2011/schwarz-evil-hangman/
My link to all my code: https://github.com/michaelbao00/Evil-Hangman
My code for my main class (titled Hangman):
import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Hangman {
public static Scanner scan = new Scanner(System.in);
public static void main(String[] args) throws IOException {
Hangman Game = new Hangman();
Game.startGame();
}
public Hangman() {
}
public void startGame() throws IOException{
System.out.println("How long do you want the word to be? (The input must be an integer) \n");
int wordLength = scan.nextInt();
findWords(wordLength);
}
public void findWords(int length) throws IOException{
FileReader filereader = new FileReader("dictionary1.txt");
BufferedReader reader = new BufferedReader(filereader);
String word=reader.readLine();
ArrayList<String> wordList = new ArrayList();
for(int i = 0; i < 100; i++){
word = reader.readLine();
if(word.length()==length){
wordList.add(word);
}
}
}
}
Code for RealHangMan class:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
public class RealHangMan {
public final String DICTIONARY = "dictionary1.txt";
private final int NUMGUESS = 6;
private ArrayList<String> _activeList;
private int _L;
private String[] _currentAnswer;
private int _shownLetters;
private int _triesRemaining;
private boolean _gameOver;
private ArrayList<String> _guessed;
private List<String> alphabet = Arrays.asList("abcdefghijklmnopqrstuvwxyz".split(""));
public RealHangMan(int length, String dictionary) throws IOException {
_L = length;
_gameOver = false;
_triesRemaining = NUMGUESS;
_guessed = new ArrayList<String>(NUMGUESS);
_currentAnswer = new String[_L];
for (int i = 0; i < _L; i++) {
_currentAnswer[i] = "_";
}
_shownLetters = 0;
_activeList = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(DICTIONARY));
try {
String line = br.readLine();
while (line != null) {
if(line.length() == _L) {
String[] chars = line.split("");
List<String> charlist = Arrays.asList(chars);
HashSet s = new HashSet(charlist);
if (s.size() == _L) {
_activeList.add(line);
}
}
line = br.readLine();
}
} finally {
br.close();
}
}
public void printSortedGuesses() {
Collections.sort(_guessed);
if(_guessed.size() <= 13) {
System.out.println("Guessed " + _guessed);
} else {
ArrayList<String> rest = new ArrayList<String>();
for (String s : alphabet) {
if(! _guessed.contains(s)) {
rest.add(s);
}
}
System.out.println("Not Guessed " + rest);
}
}
public boolean isGameOver() {
return _gameOver;
}
public void displayAnswer() {
StringBuilder sb = new StringBuilder();
for (String s : _currentAnswer) {
sb.append(s);
sb.append(" ");
}
System.out.println(sb.toString());
}
public void showActiveList() {
System.out.println("Active list has " + _activeList.size() + " words:");
for (String w : _activeList) {
System.out.println(w);
}
System.out.println();
}
public void update(String letter) {
_guessed.add(letter);
ArrayList<ArrayList<String>> candidateSets = new ArrayList<ArrayList<String>>();
for (int i = 0; i < _L+1; i++) {
candidateSets.add(new ArrayList<String>());
}
//System.out.println("Pre: Size of activelist: " + _activeList.size());
for( String word : _activeList) {
String[] wordArray = word.split("");
boolean notFound = true;
for (int i = 0; i < _L; i++) {
if (wordArray[i].equals(letter)) {
notFound = false;
candidateSets.get(i).add(word);
}
}
if (notFound) {
candidateSets.get(_L).add(word);
}
}
int maxIndex = 0;
int max = -1;
for (int i = 0; i < _L + 1; i++) {
int len = candidateSets.get(i).size();
// System.out.println("Candidate Set " + i + " len " + len);
if (len > max) {
max = len;
maxIndex = i;
}
}
if (maxIndex == _L) {
_triesRemaining--;
if (_triesRemaining == 0){
System.out.println("You lose");
showActiveList();
_gameOver = true;
} else {
System.out.print("Tries:" + _triesRemaining + " ");
}
} else {
_currentAnswer[maxIndex] = letter;
displayAnswer();
_shownLetters++;
if (_shownLetters == _L) {
System.out.println("You win");
_gameOver = true;
}
}
_activeList = candidateSets.get(maxIndex);
System.out.print("Uncertainty: " + _activeList.size() + " ");
printSortedGuesses();
}
public static void main(String[] args) throws Exception {
String dict = args[0];
System.out.println("dict " + dict);
Scanner in = new Scanner(System.in);
System.out.println("Please input a wordlength");
int wordlength = in.nextInt();
RealHangMan game = new RealHangMan(wordlength , dict);
while (! game.isGameOver()) {
game.displayAnswer();
System.out.print("Please guess a letter. ");
String letter = in.nextLine();
game.update(letter);
}
in.close();
}
}
dictionary1.txt file : http://nifty.stanford.edu/2011/schwarz-evil-hangman/dictionary.txt
someone can help me with code?
How to search in text file any word and count how many it were repeated?
For example test.txt:
hi
hola
hey
hi
bye
hoola
hi
And if I want to know how many times are repeated in test.txt word "Hi" program must say "3 times repeated"
I hope you understood what I want, thank you for answers.
public int countWord(String word, File file) {
int count = 0;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(word))
count++;
}
return count;
}
HashMap h=new HashMap();
FileInputStream fin=new FileInputStream("d:\\file.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fin));
String n;
while((n=br.readLine())!=null)
{
if(h.containsKey(n))
{
int i=(Integer)h.get(n);
h.put(n,(i+1));
}
else
h.put(n, 1);
}
now iterate through this map to get the count for each word using each word as a key to the map values
Apache Commons - StringUtils.countMatches()
Use MultiSet collection from google guava library.
Multiset<String> wordsMultiset = HashMultiset.create();
Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
wordsMultiset.add(scanner.nextLine());
}
for(Multiset.Entry<String> entry : wordsMultiset ){
System.out.println("Word : "+entry.getElement()+" count -> "+entry.getCount());
}
package File1;
import java.io.BufferedReader;
import java.io.FileReader;
public class CountLineWordsDuplicateWords {
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br =null;
String [] stringArray;
int counLine = 0;
int arrayLength ;
String s="";
String stringLine="";
try{
fr = new FileReader("F:/Line.txt");
br = new BufferedReader(fr);
while((s = br.readLine()) != null){
stringLine = stringLine + s;
stringLine = stringLine + " ";/*Add space*/
counLine ++;
}
System.out.println(stringLine);
stringArray = stringLine.split(" ");
arrayLength = stringArray.length;
System.out.println("The number of Words is "+arrayLength);
/*Duplicate String count code */
for (int i = 0; i < arrayLength; i++) {
int c = 1 ;
for (int j = i+1; j < arrayLength; j++) {
if(stringArray[i].equalsIgnoreCase(stringArray[j])){
c++;
for (int j2 = j; j2 < arrayLength; j2++) {
stringArray[j2] = stringArray[j2+1];
arrayLength = arrayLength - 1;
}
}//End of If block
}//End of Inner for block
System.out.println("The "+stringArray[i]+" present "+c+" times .");
}//End of Outer for block
System.out.println("The number of Line is "+counLine);
System.out.println();
fr.close();
br.close();
}catch (Exception e) {
e.printStackTrace();
}
}//End of main() method
}//End of class CountLineWordsDuplicateWords
package somePackage;
public static void main(String[] args) {
String path = ""; //ADD YOUR PATH HERE
String fileName = "test2.txt";
String testWord = "Macbeth"; //CHANGE THIS IF YOU WANT
int tLen = testWord.length();
int wordCntr = 0;
String file = path + fileName;
boolean check;
try{
FileInputStream fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while((strLine = br.readLine()) != null){
//check to see whether testWord occurs at least once in the line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if(check){
//get the line, and parse its words into a String array
String[] lineWords = strLine.split("\\s+");
for(String w : lineWords){
//first see if the word is as least as long as the testWord
if(w.length() >= tLen){
/*
1) grab the specific word, minus whitespace
2) check to see whether the first part of it having same length
as testWord is equivalent to testWord, ignoring case
*/
String word = w.substring(0,tLen).trim();
if(word.equalsIgnoreCase(testWord)){
wordCntr++;
}
}
}
}
}
System.out.println("total is: " + wordCntr);
//Close the input stream
br.close();
} catch(Exception e){
e.printStackTrace();
}
}
public class Wordcount
{
public static void main(String[] args)
{
int count=0;
String str="hi this is is is line";
String []s1=str.split(" ");
for(int i=0;i<=s1.length-1;i++)
{
if(s1[i].equals("is"))
{
count++;
}
}
System.out.println(count);
}
}
You can read text file line by line. I assume that each line can contain more than one word. For each line, you call:
String[] words = line.split(" ");
for(int i=0; i<words.length; i++){
if(words[i].equalsIgnoreCase(searhedWord))
count++;
}
try using java.util.Scanner.
public int countWords(String w, String fileName) {
int count = 0;
Scanner scanner = new Scanner(inputFile);
scanner.useDelimiter("[^a-zA-Z]"); // non alphabets act as delimeters
String word = scanner.next();
if (word.equalsIgnoreCase(w))
count++;
return count;
}
Try it this way with Pattern and Matcher.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Dem {
public static void main(String[] args){
try {
File f = new File("d://My.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = new String();
while((s=br.readLine())!=null){
s = s + s;
}
int count = 0;
Pattern pat = Pattern.compile("it*");
Matcher mat = pat.matcher(s);
while(mat.find()){
if(mat.find()){
mat.start();
count++;
}
}
System.out.println(count);
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String ar[])throws Exception
BufferedReader br=new BufferedReader(new FileReader("c:/file.txt"));
System.out.println("enter the string which you search");
Scanner ob=new Scanner(System.in);
String str=ob.next();
String str1="",str2="";
int count=0;
while((str1=br.readLine())!=null)
{
str2 +=str1;
}
int index = str2.indexOf(str);
while (index != -1) {
count++;
str2 = str2.substring(index + 1);
index = str2.indexOf(str);
}
System.out.println("Number of the occures="+count);
}
}
package com.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception{
BufferedReader bf= new BufferedReader(new FileReader("src/test.txt"));
Scanner sc = new Scanner(System.in);
String W=sc.next();
//String regex ="[\\w"+W+"]";
int count=0;
//Pattern p = Pattern.compile();
String line=bf.readLine();
String s[];
do
{
s=line.split(" ");
for(String a:s)
{
if(a.contains(W))
count++;
}
line=bf.readLine();
}while(line!=null);
System.out.println(count);
}
}
public int occurrencesOfHi()
{
String newText = Text.replace("Hi","");
return (Text.length() - newText.length())/2;
}