Counting words, characters and lines - java

The method is to return an array counting the number of lines, words and characters in a document. After running it through a test file I am still receiving some errors.
public static int[] wc(Reader in) throws IOException {
int data = in.read();
int charcounter = 0;
int linecounter = 0;
int wordcounter = 0;
boolean previouswhitespace = false;
while (data != -1){
if (((char) data == '\n')){
linecounter++;
}
if (!(Character.isWhitespace((char) data))){
charcounter++;
if ((previouswhitespace == true) || (wordcounter == 0)){
previouswhitespace = false;
wordcounter++;
}
}
else if ((Character.isWhitespace((char) data))){
previouswhitespace = true;
}
data = in.read();
}
int[] array = {linecounter, wordcounter, charcounter};
return array;
}

//To choose the file
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
String file_path = file.getAbsolutePath();
char[] c;
String [] words;
int charCounter = 0 ,wordsCounter = 0, lineCounter = 0;
//try and catch for the BufferedReader
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader(file_path));
while( (line = reader.readLine()) !=null){
c = line.replace(" ","").toCharArray();
charCounter+=c.length;
words = line.split(" ");
wordsCounter+=words.length;
lineCounter++;
}
}catch(Exception e){
// Handle the Exception
}
int array[] = {charCounter , wordsCounter, lineCounter};
Hope this is helping you!

Related

Java set array size of 2D-array after declaration

I have a method that should return a 2D-array which is always structured like this:
int [][] = {{100}, {5}, {1,5,7,8,30,60,...}
My problem is that when I call the method I don't know how long the 3rd array will be. This is my code right now:
public static int[][] readFile(int max, int types, String fileName) {
int [][]result = new int[3][];
try {
FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println(line);
if (currentLine == 0) {
result[0][0] = Integer.parseInt(numbers[0]);
result[1][0] = Integer.parseInt(numbers[1]);
}else if (currentLine == 1) {
int []theSlices = new int[numbers.length];
result[2][0] = theSlices; //-> obviously error
for(int i = 0; i<numbers.length; i++) {
theSlices[i] = Integer.parseInt(numbers[i]);
}
return result;
}
currentLine++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
;
return null;
}
My code right now is obviously not working but how can I fix it? Happy for every help :)

Array CompareFind Equals words only using array not array list

Have a two text file with words list. need save both file in two array.I know how to do it using list and set.. but here I want know how to do it using only arrays.Only array and no predefined functions such as Arrays.sort() or Collections.sort() can be used
no list no ArrayList or no class from Java Collection Frameworks can be used.
public class Main {
public static Set<String> setlist1= new HashSet<>();
public static String[] arrayList=new String[file1count];
public static String[] array2=new String[file2count];
public static int file1count=0;
public static int file2count=0;
public static void main(String[] args) {
try {
/*read the files*/
Scanner rf= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt")));
Scanner rf2= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt")));
String line;
String line2;
while(rf.hasNext()){
line=rf.nextLine();
file1count++;
}
while(rf2.hasNext()){
line2=rf2.nextLine();
file2count++;
}
rf.close();
rf2.close();
}catch(IOException e){
System.out.println(e);
}
}
}
The problem with using arrays is that you don't know in advance what length to allocate.
You basically have two options:
read each file twice
allocate an array of some initial length, and reallocate is as needed (that's what an ArrayList does.)
Second option: let's have a method readFile that reads all the lines from a file and returns an array:
public static String[] readFile(String fileName) throws IOException {
try (Reader reader = new FileReader(fileName);
BufferedReader in = new BufferedReader(reader)) {
String[] lines = new String[10]; // start with 10
int count = 0;
String line;
while ((line = in.readLine()) != null) {
if (count >= lines.length) {
lines = reallocate(lines, count, 2*lines.length);
}
lines[count++] = line;
}
if (count < lines.length) {
// reallocate to the final length;
lines = reallocate(lines, count, count);
}
return lines;
}
}
private static String[] reallocate(String[] lines, int count,
int newLength) {
String[] newArray = new String[newLength];
for (int i = 0; i < count; ++i) {
newArray[i] = lines[i];
}
lines = newArray;
return lines;
}
BufferedReader reader1 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt"));
BufferedReader reader2 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt"));
String line1 = reader1.readLine();
String[] array1 = new String[10000000];
String[] array2 = new String[10000000];
String line2 = reader2.readLine();
boolean areEqual = true;
int lineNum = 1;
while (line1 != null || line2 != null) {
if (line1 == null || line2 == null) {
areEqual = false;
break;
} else if (!line1.equalsIgnoreCase(line2)) {
areEqual = false;
break;
}
if (line1 != null) {
array1[lineNum] = line1;
}
if (line1 != null) {
array2[lineNum] = line2;
}
line1 = reader1.readLine();
line2 = reader2.readLine();
lineNum++;
}
if (areEqual) {
System.out.println("Same content.");
} else {
System.out.println("different content");
}
reader1.close();
reader2.close();
You can simply try above code.
Here I had used only WHILE loop, BufferedReader and FileReader.

Replace letters with *

Making a hangman style of game
I have the random word now. How do I replace the letters of the word with an asterix * so that when the program starts the word is shown as *.
I assume that when someone inputs a letter for the hangman game you get the index of that character in the word and then replace the corresponding *.
public class JavaApplication10 {
public static String[] wordArray = new String[1];
public static String file_dir = "Animals.txt";
public static String selectedWord = "";
public static char[] wordCharacter = new char[1];
Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
wordArray = get_word(file_dir);
selectedWord = select_word(wordArray);
System.out.println(selectedWord);
}
public static String[] get_word(String file_dir) throws IOException {
FileReader fileReader = new FileReader(file_dir);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static String select_word(String[] wordArray) {
Random rand = new Random();
int lines = Math.abs(rand.nextInt(wordArray.length)- 1);
return wordArray[lines];
}
}
If you know how many lines are there you could use Random method in java with a specific range to pick out a line at random.
Then you could read the file line-by-line till you reach that random line and print it.
// Open the file
FileInputStream fstream = new FileInputStream("testfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int counter=0;
//While-loop -> Read File Line By Line till the end of file
//And will also terminate when the required line is printed
while ((strLine = br.readLine()) != null && counter!=randomValue){
counter++;
//You need to set randomValue using the Random method as suggested
if(counter==randomValue)
// Print the content on the console
System.out.println (strLine+"\n");
}
//Close the input stream
br.close();
Assuming Java 8:
// Loading ...
Random R = new Random(System.currentTimeMillis());
List<String> animals = Files.readAllLines(Paths.get(path));
// ...
// When using
String randomAnimal = animals.get(R.nextInt(animals.size()));
Answer of your first question :
First you have to get the total number of lines
Then you have to generate a random number between 1 and that total number.
Finally, get the required word
try {
InputStream is = new BufferedInputStream(new FileInputStream("D:\\test.txt"));
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
int noOfLines = count+1;
System.out.println(noOfLines);
Random random = new Random();
int randomInt = random.nextInt(noOfLines);
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader bufferedReader =
new BufferedReader(fr);
String line = null;
int counter =1;
while((line = bufferedReader.readLine()) != null) {
if(counter == randomInt)
{
System.out.println(line); // This the word you want
}
counter++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
//is.close();
}

how to add 2lac line in txt file by java in minimum time?

I am trying to add almost 2lac lines in particular txt file(actually conf file) by java program. But it takes almost 112 min when number is only 189000!
I write following code for that
import java.io.*;
public class Fileshandling_example {
static long s1;
static long e1;
static long e2;
static Fileshandling_example fhe= new Fileshandling_example();
public static void main(String args[]) {
try {
s1 = System.nanoTime();
File file1 = new File("\example\mandar.txt");
LineNumberReader lnr1 = new LineNumberReader(new FileReader(file1));
BufferedReader br1 = new BufferedReader(new FileReader(file1));
lnr1.skip(Long.MAX_VALUE);
int a = 1;
StringBuffer sb1 = new StringBuffer("[stations]");
String sCurrentline1 = br1.readLine();
while ((sCurrentline1 = br1.readLine()) != null) {
a++;
if (sCurrentline1.contentEquals(sb1) == true) {
int count = a;
int arraycount = 100000;
for(int i =0; i< (arraycount+1); i++){
if(0 == (i%10000)){
e2 = System.nanoTime();
System.out.println("Time = "+(e2-s1));
}
String abc ="extern => 00"+(1000 + (arraycount-i))+",1,Wait(0.05)";
fhe.insertintoExtensions(file1, (count+1),abc);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
e1 = System.nanoTime();
System.out.println("Time = "+(e1-s1));
}
public void insertintoExtensions(File inFile1, int lineno, String s1)throws Exception {
File outFile1 = new File("\example\111.tmp");
FileInputStream fis = new FileInputStream(inFile1);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile1);
PrintWriter out = new PrintWriter(fos);
String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(s1);
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();
inFile1.delete();
outFile1.renameTo(inFile1);
}
}
Can any one help me where i get wrong?
I asked similar question coderanch but here i get clue very fast so i ask here also.
Sorry for that (cross forum asking).
Thanks.
You are loop 100,000 times for every '[stations]' found on "\example\mandar.txt":
if (sCurrentline1.contentEquals(sb1) == true) {
int count = a;
int arraycount = 100000;
for(int i =0; i< (arraycount+1); i++){
and call fhe.insertintoExtensions which loops "\example\mandar.txt" again to copy or the content of the line or the content of s1 parameter until the actual line number is reached:
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(s1);
out.println(thisLine);
i++;
}
Try to improve you code and use BufferedWriter instead of PrintWriter.

How to replace a String at a specific index in a text file in Java

My text file contains:
Hello This is a Test
Press Enter to Continue
I have an array of:
int StartIndex [] = {1,4,8}
int EndIndex [] = {3,7,11}
String[] VALUES = new String[] {"Sys","Jav","Tes"};
I want to replace index{1,3} with 'Sys', index{4,7} with 'Jav' and so on in the file.
My idea is to read the whole file as a String and then pass on the indexes to replace with the VALUES Strings.
How can I do this ?
CODE:
String[] VALUES = new String[] {"Sys"}; //Correct Solutions
int [] StartIndex ={4};
int [] EndIndex ={6};
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println (line);
StringBuffer buf = new StringBuffer(line);
buf.replace(StartIndex[0], EndIndex[0], VALUES[0]);
done =buf.toString();
System.out.println(done);
Expected Ouput should be like this:
SyslJavhTes is a Test
Press Enter to Continue
I searched a bit and got this:
String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
If we convert the file to string and apply this function ,will this work?
Problem Solved! Code works perfectly because I tested it. Like before no comments have been added so you will understand & learn. (Please vote/accept answer if it works for others to identify the correct answer).
CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
*
* #author jtech
*/
public class ReplaceWithIndexes
{
public static void main(String[] args) throws IOException
{
BufferedReader br = null;
boolean endMatched = false;
int startIndex[] = {0,4,8};
int endIndex[] = {3,7,10};
int c = 0, c1 = 0, c2 = 0, largestVal_start = 0, largestVal_end = 0, lineCount = 0;
String line = null, newString = "";
String[] VALUES = new String[] {"Sys","Jav","Tes"};
br = new BufferedReader(new FileReader("C:\\Users\\jtech\\Documents\\NetBeansProjects\\HelpOthers\\src\\textFiles\\AnotherFile.txt"));
for (int i = 0; i < startIndex.length; i++)
{
if (startIndex[i] > largestVal_start)
{
largestVal_start = startIndex[i];
}
}
for (int i = 0; i < endIndex.length; i++)
{
if (endIndex[i] > largestVal_end)
{
largestVal_end = endIndex[i];
}
}
while ((line = br.readLine()) != null)
{
StringBuilder buf = new StringBuilder(line);
// Print the content on the console
System.out.println(line);
lineCount++;
while (c <= largestVal_start)
{
while (c1 <= largestVal_end)
{
if (startIndex[0] == c && endIndex[0] == c1)
{
buf.replace(startIndex[0], endIndex[0], VALUES[c2]);
newString = buf.toString();
endMatched = true;
}
else if (startIndex[1] == c && endIndex[1] == c1)
{
buf.replace(startIndex[1], endIndex[1], VALUES[c2]);
newString = buf.toString();
endMatched = true;
}
else if (startIndex[2] == c && endIndex[2] == c1)
{
buf.replace(startIndex[2], endIndex[2], VALUES[c2]);
newString = buf.toString();
endMatched = true;
}
c1++;
}
for (int i = 0; i < startIndex.length; i++)
{
if (c == startIndex[i])
{
c2++;
}
}
if (endMatched == true || ((c1 <= largestVal_end) == false) )
{
c1 = 0;
endMatched = false;
}
c++;
}
if (lineCount <= 1)
{
System.out.println("Updated line: " + newString);
}
}
}
}
In Java, the class is the proverbial hammer and every problem really is a nail. You need one for your case, too, instead of managing three separate arrays.
class Replacer {
private final int start, end;
private final String replacement;
Replacer(int start, int end, String replacement) {
this.start = start; this.end = end; this.replacement = replacement;
}
String replace(String in) {
StringBuilder b = new StringBuilder(in);
b.replace(start, end, replacement);
return b.toString();
}
}
Then create a list of replacers:
List<Replacer> replacers = Arrays.asList(
new Replacer(1, 3, "System"),
new Replacer(4, 7, "Java"),
new Replacer(8, 11, "Testing")
);
and apply them on each line:
while ((line = br.readLine()) != null) {
for (Replacer r : replacers) line = r.replace(line);
System.out.println(line);
}
The simplest solution would be the following code, but it's probably not efficient enough for huge files and/or large numbers of replaces.
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println (line);
StringBuffer buf = new StringBuffer(line);
for (int i = 0; i < VALUES.length; i ++) {
buf = buf.replace(StartIndex[i], EndIndex[i], VALUES[i]);
}
done = buf.toString();
System.out.println(done);
}

Categories