combine two methods in Java together in this Java code - java

I want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
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
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
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
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!

Related

how can I write a code to read each name in a file

I typed 3 names in the file, and I wanted to write a code to count how many times each name was repeated (Example: Alex was repeated in the file 3 times..and so on). The code I wrote only counted each name once, and this is wrong because the names were repeated more than once. Can you help me with the part that could be the cause of this problem?
public class MainClass {
public static void readFile() throws IOException {
//File file;
FileWriter writer=null;
String name, line;
List <String> list = new ArrayList <>();
int countM = 0, countAl = 0, countAh = 0;
try
{
File file = new File("\\Users\\Admin\\Desktop\\namesList.txt");
Scanner scan = new Scanner(file);
while(scan.hasNextLine()) {
line = scan.nextLine();
list.add(line);
}
for (int i=0; i<list.size(); i++)
{
name=list.get(i);
if (name.equals("Ali"))
{
countAl= +1;
}
if (name.equals("Ahmed"))
{
countAh= +1;
}
if (name.equals("Muhammad"))
{
countM = +1;
}
}
Collections.sort(list);
writer = new FileWriter("\\Users\\Admin\\Desktop\\newNameList");
for(int i=0; i<list.size(); i++)
{
name = list.get(i);
writer.write(name +"\n");
}
writer.close();
System.out.println("How many times is the name (Ali) in the file? " + countAl);
System.out.println("How many times is the name (Ahmed) in the file? " + countAh);
System.out.println("How many times is the name (Muhammad) in the file? " + countM);
}
catch(IOException e) {
System.out.println(e.toString());
}
}
public static void main(String[] args) throws IOException {
readFile();
}
}
You an do this much simpler:
//Open a reader, this is autoclosed so you don't need to worry about closing it
try (BufferedReader reader = new BufferedReader(new FileReader("path to file"))) {
//Create a map to hold the counts
Map<String, Integer> nameCountMap = new HashMap<>();
//read all of the names, this assumes 1 name per line
for (String name = reader.readLine(); name != null; name = reader.readLine()) {
//merge the value into the count map
nameCountMap.merge(name, 1, (o, n) -> o+n);
}
//Print out the map
System.out.println(nameCountMap);
} catch (IOException e) {
e.printStackTrace();
}
try:
for (int i=0; i<list.size(); i++)
{
name=list.get(i);
if (name.equals("Ali"))
{
countAl += 1;
}
if (name.equals("Ahmed"))
{
countAh += 1;
}
if (name.equals("Muhammad"))
{
countM += 1;
}
}
This works with me.
+= is not same =+
You need to process each line bearing in mind that the file may be very large in some cases. Better safe than sorry. You need to consider a solution that does not take up so much resources.
Streaming Through the File
I'm going to use a java.util.Scanner to run through the contents of the file and retrieve lines serially, one by one:
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(file_path);
sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
// System.out.println(line);
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
This solution will iterate through all the lines in the file – allowing for processing of each line – without keeping references to them – and in conclusion, without keeping them in memory:
Streaming With Apache Commons IO
The same can be achieved using the Commons IO library as well, by using the custom LineIterator provided by the library:
LineIterator it = FileUtils.lineIterator(your_file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
LineIterator.closeQuietly(it);
}
Since the entire file is not fully in memory – this will also result in pretty conservative memory consumption numbers.
BufferedReader
try (BufferedReader br = Files.newBufferedReader(Paths.get("file_name"), StandardCharsets.UTF_8)) {
for (String line = null; (line = br.readLine()) != null;) {
// Do something with the line
}
}
ByteBuffer
try (SeekableByteChannel ch = Files.newByteChannel(Paths.get("test.txt"))) {
ByteBuffer bb = ByteBuffer.allocateDirect(1000);
for(;;) {
StringBuilder line = new StringBuilder();
int n = ch.read(bb);
// Do something with the line
}
}
The above examples will process lines in a large file without iteratively, without exhausting the available memory – which proves quite useful when working with these large files.

How to read float values from a file and initialize array?

i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
}
You need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]

Dealing with txt file via split(), says Nullpointerexception

I know there are many similar questions here, but I still can't solve it. I can get all the results that I want. However, in the end, it still shows nullpointerexception. I don't know why. can anyone help?
public class PointGenterate {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
try{
File file = new File("123.txt");
double[] pointsid = new double[10];
String[] data = null;
for(int i = 0; i <10; i++){
double rn = (int)(Math.random()*120);
System.out.println(rn);
pointsid[i] = rn;
}
//read file
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
line = br.readLine();
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while(line != null){
line = br.readLine();
if(line==" "){
System.out.print("empty");
}else{
data = line.split(",|:|[|]");
}
for(int i = 0; i < data.length; i++){
data[i] = data[i].trim();
System.out.println(data[i] + "num" + i);
}
if(data.length > 15){
double id = Double.parseDouble(data[4]);
for(int i = 0; i <10; i++){
if(id == pointsid[i]){
data[10] = data[10].substring(0, data[10].length()-2);
data[15] = data[15].substring(1,data[15].length());
data[16] = data[16].substring(0, data[16].length()-6);
out.write(data[8]+" "+ data[10]+ " " + data[13] + data[15] + data[16]+ "\r\n");
out.flush();
}
}
}
//System.out.println(line);
}
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
the txt file format is like
{ "type": "Feature", "properties": { "id": 126.000000, "osm_id": 4851918786.000000, "name": "Moray House Library", "type": "library" }, "geometry": { "type": "Point", "coordinates": [ -3.180841771200988, 55.950622362732418 ] } },
this is one line. I have many lines, and actually this is just a test code. if it works. i want to write it as a method in a javaseverlet class. get the string coordinates and return it to my JS font-end.
There's a few issues with your code. In this section:
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
line = br.readLine(); // here you read the first line in the file
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while(line != null){ // here you check that it's not null (it's not, you read the first line OK)
line = br.readLine(); // here you read the second line (there is no second line, now line is null)
if(line==" "){ // now you check if the line is a space character (this is wrong for 2 reasons, that's not how you compare strings, and a space character is not an empty string)
System.out.print("empty");
}else{
data = line.split(",|:|[|]"); // here you call split() on line but line is null
}
When you checked if the string was empty, you did line == " " which is wrong for 2 reasons. First you cannot use == to compare strings - read this question for details on why not. Second, " " is a string that contains a space character. "" is an empty string.
When you want to check if a string is empty you can do it like this:
line.equals("")
or like this:
line.isEmpty()
Here's your code with a few small changes so that it runs without throwing an exception.
public class PointGenterate {
public static void main(String[] args) throws Exception {
try {
File file = new File("123.txt");
double[] pointsid = new double[10];
String[] data = null;
for(int i = 0; i < 10; i++){
double rn = (int)(Math.random()*120);
System.out.println(rn);
pointsid[i] = rn;
}
//read file
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while((line = br.readLine()) != null){ // read the line and check for null
if(line.isEmpty()) { // is the line equal to the empty string?
System.out.print("empty");
} else {
data = line.split(",|:|[|]");
}
for(int i = 0; i < data.length; i++){
data[i] = data[i].trim();
System.out.println(data[i] + "num" + i);
}
if(data.length > 15){
double id = Double.parseDouble(data[4]);
for(int i = 0; i <10; i++){
if(id == pointsid[i]){
data[10] = data[10].substring(0, data[10].length()-2);
data[15] = data[15].substring(1,data[15].length());
data[16] = data[16].substring(0, data[16].length()-6);
out.write(data[8]+" "+ data[10]+ " " + data[13] + data[15] + data[16]+ "\r\n");
out.flush();
}
}
}
//System.out.println(line);
}
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}

To print the given rows of string into columns

I have *.txt file with first row as name,address,mail id and second line with the values. I have to print this into two columns,the first one with the headings and second with the value using Java. how do I do this?
public class ReadFile1 {
public static void main(String[] args) {
BufferedReader br=null;
String sCurrentLine = null;
String delimiter = ",";
String[] filetags;
try {
br = new BufferedReader(new FileReader("path\\Read.txt"));
sCurrentLine = br.readLine();
StringBuffer result = new StringBuffer();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
filetags = line.split(delimiter);
for(int i = 0;i < line.length(); i++)
{
System.out.println("****" +sCurrentLine);
String[] s = line.split(",");
for(int j = i-1; j<line.length();j++)
{
System.out.println("##############"+Arrays.toString(s));
}
}
}
}
This is what I tried. Ex: I have a file say,
line1) name,email,mobile and second
line2) john,j#abc.com,9876
line3) max,max#xyz.com,1234
Now, I need to print:
name john
email john#abc.com
moblie 9876
name max
email max#xyz.com
mobile 1234
Below is one way you may be able to get what you want, It is similar to how you have attempted but slightly more refined.
The File:
name,email,mobile and second
john,j#abc.com,9876
max,max#xyz.com,1234
The code:
//File is on my Desktop
Path myFile = Paths.get(System.getProperty("user.home")).resolve("Desktop").resolve("tester.txt");
//Try-With-Resources so we autoclose the reader after try block
try(BufferedReader reader = new BufferedReader(new FileReader(myFile.toFile()))){
String[] headings = reader.readLine().split(",");//Reads First line and gets headings
String line;
while((line = reader.readLine()) != null){//While there are more lines
String[] values = line.split(","); //Get the values
for(int i = 0; i < values.length; i++){//For each value
System.out.println(headings[i] + ": " + values[i]);//Print with a heading
}
}
} catch (IOException io) {
io.printStackTrace();
}
Good Luck!
Something like this should do the trick.
Read the file and store each line in a list.
Iterate through the list of lines
If it is safe to assume the first line will always be the title line, take the input and store it in a collection.
For the rest of the lines, split on the comma and use the index of the splitter array to refer to the title column.
List <String> lines = new ArrayList<String>();
Scanner scanner = new Scanner(new File("FileName.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
lines.add(line);
}
scanner.close();
int lineNo = 0;
List <String> title = new ArrayList<String>();
for(String line : lines){
if(lineNo == 0){
String [] titles = line.split(",");
for(String t : titles){
title.add(t);
}
lineNo++;
}
else{
String input = line.split(",");
for(int i = 0; i<input.length; i++){
System.out.println(title.get(i) + ": " + input[i]);
}
lineNo++;
}
}

How to assign a text file's lines of integers into 2D tables in Java?

I have the sample.txt which contains 100 Integers (range 0-9) in every line formatted like this:
9 2 0 3 4 1 0 7 5 3 7 8 6 2 0 1 4 4 5 9 0 3 2 1 7 (etc... 100 numbers)
I want to scan the file and put every line into a 10x10 table. So:
public void loadTableFromFile(String filepath){
try (Scanner s = new Scanner(new BufferedReader(new FileReader(filepath)))) {
String line;
while (s.hasNextLine()) {
// WHAT HERE? THIS BLOCK DOES NOT WORK
/* if (s.hasNextInt()) {
//take int and put it in the table in the right position procedure
} else {
s.next();
} */
// END OF NOT WORKING BLOCK
}
} catch (FileNotFoundException e){
}
}
How about something like this?
public void loadTableFromFile(String filepath) {
Scanner s = null; // Our scanner.
try {
s = new Scanner(new BufferedReader(
new FileReader(filepath))); // get it from the file.
String line;
while (s.hasNextLine()) { // while we have lines.
line = s.nextLine(); // get a line.
StringTokenizer st = new StringTokenizer(line, " ");
int i = 0;
while (st.hasMoreTokens()) {
if (i != 0) {
System.out.print(' '); // add a space between elements.
}
System.out.print(st.nextToken().trim()); // print the next element.
i++;
if (i % 10 == 0) { // Add a new line every ten elements.
System.out.println();
}
}
System.out.println(); // between lines.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (s != null)
s.close();
}
}
Here is a solution that reads the line of the file into an array of strings using the split by whitespace method, and then reads them in using a for loop. I threw any exceptions that might have occurred in the method declaration, alternatively, use the try catch loop as above (might be better design, not sure about that.)
public void loadTableFromFile(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String[] line = br.readLine().split(" ");
br.close(); // file only has 1 line with 100 integers
int[][] mydata = new int[10][10];
for(int i = 0; i < line.length; i++) {
mydata[i % 10][(int) (i / 10)] = Integer.parseInt(line[i]);
}
}
Now, if the file has more than one line, you could instead read the entire file line by line, and then use the above idea like this:
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line1;
while((line1 = br.readLine()) != null) {
String[] line = line1.split(" ");
... // do above stuff of reading in 1 line here
}
br.close();
Try,
try (Scanner s = new Scanner(new BufferedReader(new FileReader(filepath)))) {
String line;
while (s.hasNextLine()) {
String[] strArr=line.split(" ");
for(int i=0;i<strArr.length;i++){
System.out.print(" "+strArr[i]);
if((i+1)%10==0){
System.out.println();
}
}
}
} catch (FileNotFoundException e){
}

Categories