How to access a textfile entering its name in console? JAVA -
what should 1 change in code instead of entering string in console, 1 enters text name (exmple.txt) text (where frequences counted)?
import java.io.*; class frequencycount { public static void main(string args[]) throws ioexception { bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); system.out.println ("enter text: "); string s = br.readline(); system.out.println ("enter suffix: "); string sub = br.readline(); int ind,count = 0; for(int = 0; + sub.length() <= s.length(); i++) { ind = s.indexof(sub, i); if (ind >= 0) { count++; = ind; ind = -1; } } system.out.println("occurence of '"+sub+"' in string "+count); } }
first of refactor code in order reuse calculateocurrences method. read text file line line , sum occurrences line.
import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; import java.nio.charset.charset; import java.nio.file.filesystems; import java.nio.file.files; import java.nio.file.path; public class main { public static void main(string args[]) throws ioexception { bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); system.out.println ("enter file path: "); final string filepath = br.readline(); system.out.println ("enter suffix: "); final string suffix = br.readline(); int count = 0; path path = filesystems.getdefault().getpath(filepath); charset charset = charset.forname("us-ascii"); try (bufferedreader reader = files.newbufferedreader(path, charset)) { string line = null; while ((line = reader.readline()) != null) { count = count + calculateocurrences(line,suffix); } } catch (ioexception x) { system.err.format("ioexception: %s%n", x); } system.out.println("occurence of '"+suffix+"' in string "+count); } public static int calculateocurrences(final string text, final string suffix) { int ocurrences = 0; for(int = 0; + suffix.length() <= text.length(); i++) { int indexofocurrence = text.indexof(suffix, i); if (indexofocurrence >= 0) { ocurrences++; = indexofocurrence; } } return ocurrences; } }
Comments
Post a Comment