Trying two Link classes with Java - java

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

Related

Choosing a Random word from a text file

I'm trying to develop a hangman as an assignment, and is unable to get one random word from a Text file(which has various words and each word is separated with a space). I've written a code to get a random word, but unable to pick one words and replace it, with the sample string (String w = "this";) i have in the "Function()".
public String randomWord(String wordran) {
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt"));
String line = reader.readLine();
List<String> words = new ArrayList<String>();
while (line != null) {
String[] wordline = line.split(" ");
for (String word : wordline) {
words.add(word);
}
Random rand = new Random();
String randomWord1 = words.get(rand.nextInt(words.size()));
//System.out.println("rand word : " + randomWord1);
}
reader.close();
} catch (Exception e) {
}
return wordran;
}
public void function(){
int numGuesses = 10;
String w = randomWord();
String[] word = w.split("");
ArrayList< String> wList = new ArrayList<>(Arrays.asList(word));
ArrayList< String> wAnswer = new ArrayList< String>(wList.size());
for (int i = 0; i < wList.size(); i++) {
wAnswer.add("_ ");
}
int left = wList.size();
Scanner scanner = new Scanner(System.in);
boolean notDone = true;
ArrayList< String> lettersGuessed = new ArrayList< String>();
while (notDone) {
System.out.println();
String sOut = "";
List< String> lettersLeft = getRemainingLetters(lettersGuessed);
for (String s : lettersLeft) {
sOut += s + " ";
}
System.out.println("Letters Left: " + sOut);
sOut = "";
for (int i = 0; i < wList.size(); i++) {
sOut += wAnswer.get(i);
}
System.out.println(sOut + " Guesses left:" + numGuesses);
System.out.print("Enter a letter(* exit): ");
String sIn = scanner.next();
numGuesses--;
if (sIn.equals("*")) {
break;
}
lettersGuessed.add(sIn);
for (int i = 0; i < wList.size(); i++) {
if (sIn.equals(wList.get(i))) {
wAnswer.set(i, sIn);
left--;
}
}
if (left == 0) {
System.out.println("Congradulations you guessed it!");
break;
}
if (numGuesses == 0) {
System.out.println("You failed...:(");
break;
}
}
}
public static void main(String[] args) throws IOException {
Main ma = new Main();
ma.function();
loadWords();
// ma.randomWord();
}
There are three problems with your code:
You don't need to pass the parameter, String wordran to store the random word. A useful parameter can be String path through which you can pass the path of the file to the function.
You've missed reading the content from the file in the loop. You've read just the first line.
You haven't returned the random word which you have calculated by applying Random#nextInt.
On a side note, I recommend you use try-with-resources syntax to get rid of closing BufferedReader explicitly.
Given below is the correct code incorporating these comments:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) throws IOException {
// Test
System.out.println(getRandomWord("C:\\Users\\Admin\\Documents\\NetBeansProjects\\Main\\words.txt"));
}
public static String getRandomWord(String path) throws IOException {
List<String> words = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
String[] wordline = line.split("\\s+");
for (String word : wordline) {
words.add(word);
}
}
}
Random rand = new Random();
return words.get(rand.nextInt(words.size()));
}
}

Evil Hangman Project Java not working- My program is not allowing me to input guesses for letters

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

Why does this program terminate when I enter user input?

The program is supposed to compare a user-inputted string to a text document. If the program finds a match in the file and in part of the string, it should highlight or change the font color of the matching string in what the user inputted. The thing is, once I enter something for user input, the program terminates. Examples of inputs that could have a match in the file are MALEKRQ, MALE, MMALEKR, MMMM, and MALEK. How do I fix this problem? I'm using Eclipse Neon on Mac OS X El Capitan.
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner fileInput = new Scanner(file);
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
int len = userProteinSequence.length();
int size = 4;
int start = 0;
int indexEnd = size;
while (indexEnd < len - size)
{
for (int index = start; index <= len - size; index++)
{
String search = userProteinSequence.substring(index, indexEnd);
System.out.println(search);
while (fileInput.hasNext())
{
String MALEKRQ = fileInput.nextLine();
// System.out.println(MALEKRQ);
int found = MALEKRQ.indexOf(search);
if (found >= 0)
{
System.out.println("Yay.");
}
else
{
System.out.println("Fail.");
}
}
indexEnd++;
}
size++;
if (size > 8) {
size = 8;
start++;
}
}
}
catch (FileNotFoundException e)
{
System.err.format("File does not exist.\n");
}
}
}
import java.util.*;
import java.io.*;
public class ScienceFair
{
public static void main(String[] args) throws FileNotFoundException
{
java.io.File file = new java.io.File("/Users/Kids/Desktop/ScienceFair/src/MALEKRQsample.txt");
try
{
Scanner userInput = new Scanner(System.in);
System.out.println("Enter Protein Sequence");
String userProteinSequence = userInput.nextLine().toUpperCase();
for (int size = userProteinSequence.length(); size >= 4; size--) {
for (int start = 0; start <= userProteinSequence.length()-size; start++) {
boolean found = false;
String search = userProteinSequence.substring(start, size);
System.out.println(search);
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
int found = MALEKRQ.indexOf(search);
if (found >= 0) {
found = true;
}
}
if (found) {
System.out.println(search+" found (index "+start+")");
fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
MALEKRQ = MALEKRQ.replaceAll(search, "[["+search+"]]");
System.out.println(MALEKRQ);
}
return;
}
}
}
System.out.println(search+" not found");
Scanner fileInput = new Scanner(file);
while (fileInput.hasNext()) {
String MALEKRQ = fileInput.nextLine();
System.out.println(MALEKRQ);
}
} catch (FileNotFoundException e) {
System.err.format("File does not exist.\n");
}
}
}

making a line of text from a text file into a cipher text in java

I have a line of text that I need to decrypt into a cipher text.
Let's say my line of text is abc def ghijklm n opq rstu vwx yz
and I want an output like this: aei qu c k rvzdhmptxbfjn y glosm
lets say I entered my "key" as 5. The code then will enter every 5th element of the array o f strings of the text from the text file.
This is the code I have come up with and I have hit a wall on what to do.
import java.io.*;
import java.util.*;
public class Files1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int key;
System.out.print("Enter file: ");
String fileName = input.nextLine();
System.out.print("Please enter your Cipher Key: ");
key = input.nextInt();
Scanner inputStream = null;
System.out.println("File name is: " + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file" + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
char arrayText[] = text.toCharArray();
for (int i = 0; i < arrayText.length; i += key) {
System.out.print("\n" + arrayText[i]);
}
}
}
}
Here is whats happening in the console:
Enter file: abc.txt
File name is: abc.txt
abc def ghijklm n opq rstu vwx yz
a
e
i
q
u
What you need is a circular list.
Here is a very simple and crude implementation of a circular list using arrays.
import java.util.Iterator;
import java.util.List;
public class CircularList implements Iterator<String> {
private String[] list;
private int pointerIndex;
private int key;
public CircularList(String[] list, int key) {
this.list = list;
pointerIndex = 1 - key;
this.key = key;
}
#Override
public boolean hasNext() {
if(list.length == 0){
return false;
}
return true;
}
#Override
public String next() {
if(pointerIndex + key > list.length) {
int diff = (list.length-1) - pointerIndex;
pointerIndex = key - diff;
return list[pointerIndex];
}else {
pointerIndex = pointerIndex + key;
return list[pointerIndex];
}
}
#Override
public void remove() {
//Do Nothing
}
}
Once you have a list in which you can iterate in a circular fashion, you can change you existing implementation to this -
import java.io.*;
import java.util.*;
public class Files1 {
public static void main(String[] args) {
System.out.print("Enter file: ");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
Scanner inputStream = null;
System.out.println("" + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file: " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
String[] splits = text.split("");
CircularList clist = new CircularList(splits, 5);
for (int i = 0; i < splits.length -1; i += 1) {
System.out.print("" + clist.next());
}
}
}
}
Output -
Enter file: resources\abc.txt
resources\abc.txt
abc def ghijklm n opq rstu vwx yz
aei qu c k rvzdhmptxbfjn y glosw
Also the last character in your cipher should be 'w' and not 'm'.
You don't specify what should happen to the spaces, or what happens when wraparound is required, but assuming spaces are significant and wrap-around just happens naturally:
for (int i = 0; i < text.length(); i++)
{
System.out.print(text.charAt((i*5) % text.length()));
}
prints aei qu c k rvzdhmptxbfjn y glosw, which strongly suggests an error in your expected output.
import java.io.;
import java.util.;
public class Files1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int key;
System.out.print("Enter file: ");
String fileName = input.nextLine();
System.out.print("Please enter your Cipher Key: ");
key = input.nextInt();
Scanner inputStream = null;
System.out.println("File name is: " + fileName);
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening the file" + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String text = inputStream.nextLine();
System.out.println(text);
for (int i = 0; i < text.length(); i++) {
System.out.print(text.charAt((i * key) % text.length()));
}
}
}
}
MANY THANKS TO EJP AND Pai!
i learned alot!

Find specific word in text file and count it

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

Categories

Resources