how can i read and store reattempts? - java

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) {
}
}

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

Java word appearence in a text file

For the given text file (text.txt) compute how many times each word appears in the file. The output of the program should be another text file containing on each line a word and then the number of times it appears in the original file. After you finish change the program so that the words in the output file are sorted alphabetically. Do not use maps, use only basic arrays. The thing is displaying me only one word that I enter from keyboard in that text file, but how can I display for all words, not only for one? Thanks
package worddata;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class WordData {
public FileReader fr = null;
public BufferedReader br =null;
public String [] stringArray;
public int counLine = 0;
public int arrayLength ;
public String s="";
public String stringLine="";
public String filename ="";
public String wordname ="";
public WordData(){
try{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the filename: ");
filename = scan.nextLine();
Scanner scan2 = new Scanner(System.in);
System.out.println("Please enter a word: ");
wordname = scan.nextLine();
fr = new FileReader(filename);
br = new BufferedReader(fr);
while((s = br.readLine()) != null){
stringLine = stringLine + s;
//System.out.println(s);
stringLine = stringLine + " ";
counLine ++;
}
stringArray = stringLine.split(" ");
arrayLength = stringArray.length;
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;
}
if (stringArray[i].equalsIgnoreCase(wordname)){
System.out.println("The word "+wordname+" is present "+c+" times in the specified file.");
}
}
}
}
System.out.println("Total number of lines: "+counLine);
fr.close();
br.close();
}catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
OutputStream out = new FileOutputStream("output.txt");
System.out.println("Please enter the filename: ");
String filename = scan.nextLine();
System.out.println("Please enter a word: ");
String wordname = scan.nextLine();
int count = 0;
try (LineNumberReader r = new LineNumberReader(new FileReader(filename))) {
String line;
while ((line = r.readLine()) != null) {
for (String element : line.split(" ")) {
if (element.equalsIgnoreCase(wordname)) {
count++;
System.out.println("Word found at line " + r.getLineNumber());
}
}
}
}
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("The word " + stringBuffer.toString() + " appears " + count + " times.");
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 1000; i++) {
String str = null;
str = +i + ":- The word "+wordname+" was found " + count +" times";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
FileWriter writer = null;
try {
writer = new FileWriter("final.txt");
writer.write(listString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The code below does something like you want I think.
it does the following:
read the contents from the input.txt file
Remove punctuation marks from the text
make it one string of words by removing line breaks
Split the text up in words by using space as delimiter
The lambda maps all the words to lowercase then removes whitespace and all empty entries then it...
loops over all words and computes there word count in het HashMap
then we sort the Map based on the count value in reverse order to get the highest counted words first
then write them to a StringBuilder to format it like this "word : count\n" and then write it to a text file
final String content = new String(Files.readAllBytes(Paths.get("<PATH TO YOUR PLACE>/input.txt")));
final List<String> words = Arrays.asList(content.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").replace("\n", " ").split(" "));
final Map<String, Integer> wordlist = new HashMap<>();
words.stream()
.map(String::toLowerCase)
.map(String::trim)
.filter(s -> !s.isEmpty())
.forEach(s -> {
wordlist.computeIfPresent(s, (s1, integer) -> ++integer);
wordlist.putIfAbsent(s, 1);
});
final StringBuilder sb = new StringBuilder();
wordlist.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
)).forEach((s, integer) -> sb.append(s).append(" : ").append(integer).append("\n"));
Files.write(Paths.get("<PATH TO YOUR PLACE>/output.txt"), sb.toString().getBytes());
Hope it helps :-)
Note: the <PATH TO YOUR PLACE> needs to be replaced by the fully qualified path to your text file with words.

How to get the nextInt after the nextInt but retain the value

My problem is instead of the fixed value of iValueNext, I want the next value on the excel sheet to run, which is 125,152,...
import java.util.*;
import java.io.*;
public class ConvertingData
{
public static void main (String [] args)
{
int i=1;
int j;
int iValue;
int iValueNext;
try
{
Scanner ifsInput = new Scanner(new File("input.csv"));
PrintStream ifsOutput = new PrintStream(new File("output.csv"));
while(ifsInput.hasNextLine())
{
String tokens[] = ifsInput.nextLine().split(",");
String Repeat = tokens[tokens.length - 1];
String Value = tokens[tokens.length - 3];
iValue = Integer.parseInt( Value );
for (i=iValue;i<=iValueNext;i++)
{
System.out.println(i+","+Repeat);
ifsOutput.println(i+","+Repeat);
}
}
ifsInput.close();
ifsOutput.close();
}
catch (FileNotFoundException sMsg)
{
System.out.println("File not found");
}
}
}
Here is part of the csv file:
89,31,31
125,1,32
152,-12,20
155,1,21
181,6,27
287,1,28
290,1,29
308,-8,21
If you need to "peek" at the next line while processing the current line, first read all the lines in:
List<String> lines = new ArrayList<String>();
while(ifsInput.hasNextLine()) {
lines.add(ifsInput.nextLine());
}
ifsInput.close();
then process the lines one by one with access to the next line:
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
String nextLine = i < lines.size() - 1 ? null : lines.get(i + 1);
String tokens[] = line.split(",");
String nextTokens[] = nextLine.split(",");
// whatever logic you need
ifsOutput.close();
}

ArrayIndexOutOfBoundsException in word frequency calculation

This is my logic for word frequency. I'm not supposed to use HashMap to store the frequency of a word. I am getting an ArrayIndexoutofBoundsException, but can't figure out why.
Program:
package thirdassignments;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class WordFreq2 {
public void Working() {
try {
File file = new File("C:/Users/kishansr/Desktop/file1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
String sentence = stringBuffer.toString();
String [] words = sentence.split("\\s+"); // splits by whitespace
for (String word : words) {
System.out.println(word);
}
String word1[] = new String [100000];
int count[] = {0}, count1 = 0;
for (String word : words) {
count1 = count1 + 1;
}
System.out.println("COunt :" + count1);
for (String word : words) {
for (int i = 0 ; i < count1 ; i++) {
if (word1[i] != word) {
word1[i] = word;
count[i] = 1; // here the exception is oocuring
}
else if (word1[i] == word) {
count[i] = count[i] + 1;
}
}
}
for (int i = 0 ; i < count1 ; i++) {
System.out.println(count[i] + " : " + word1[i]);
}
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main(String [] args) {
// TODO Auto-generated method stub
WordFreq2 wf = new WordFreq2();
long startruntime = System.nanoTime();
wf.Working();
long endruntime = System.nanoTime();
System.out.println( "start time: " + startruntime + " end time :" + endruntime + " diferrence: " + (endruntime - startruntime));
}
}
Output :
This
is
the
Hewlett
Packard
company
.
This
Company
is
spread
over
the
world
and
has
established
its
footprints
in
almost
all
countries
.
It
has
a
huge
employee
count
and
has
more
women
employees
than
male
employees
.
COunt :39
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
You've instantiated the count[] array with a size of 1. It needs to be at least as large as your array.
Try change this line
String word1[]=new String[100000];
int count[]={0},count1=0;
for (String word : words) {
count1=count1+1;
}
to
String word1[]=new String[100000];
int count1=0;
for (String word : words) {
count1=count1+1;
}
count[]= new int[count1];
Your count array :
int count[]={0};
has a single element
So you'll get an exception for count[i] for any i>0.
Perhaps you should initialize it to the same length as the word1 array :
int count[]= new int[100000];
In addition, replace word1[i]==word with word1[i].equals(word).

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