Using Arraylist in different classes - java

So the code below finds words in a document as specific by the word input. Counts the number of times the words occurs in each sentence then stores that count in the arraylists at the bottom label a for cone and b for ctwo.
I want to use the arraylists in another class but can't seem to find a way to do it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class exc {
public exc() {
}
public static void main(String[] args) throws Exception {
cone aa = new cone();
ctwo bb = new ctwo();
// after this I'm stuck
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
public class cone {
public void cone() throws Exception {
BufferedReader e = new BufferedReader(new FileReader("words to be read.txt"));
String o;
while((o = e.readLine()) != null){
String[] sentences = o.split("\\b[.!?]\\s+");
//System.out.println(o);
String [] h = sentences;
{
BufferedReader t = new BufferedReader(new FileReader("Text to be scan.txt"));
String g;
while((g = t.readLine()) != null){
String[] set=g.split(" ");
List<String> list = Arrays.asList(set);
// System.out.println(Arrays.toString(set));
//System.out.println(o);
int sentenceNumb=1;
for (String sentence: h) {
int counter=0;
String[] words = sentence.replace(".", "").split(" ");
for(String word: words) {
if (list.contains(word)) {
counter++;
}
}
List<Integer> A = Arrays.asList(counter++);
}
}
}
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
public class ctwo {
public void ctwo() throws Exception {
BufferedReader e = new BufferedReader(new FileReader("words to be read.txt"));
String o;
while((o = e.readLine()) != null){
String[] sentences = o.split("\\b[.!?]\\s+");
//System.out.println(o);
String [] h = sentences;
{
BufferedReader t = new BufferedReader(new FileReader("Text to be scan.txt"));
String g;
while((g = t.readLine()) != null){
String[] set=g.split(" ");
List<String> list = Arrays.asList(set);
// System.out.println(Arrays.toString(set));
//System.out.println(o);
int sentenceNumb=1;
for (String sentence: h) {
int counter=0;
String[] words = sentence.replace(".", "").split(" ");
for(String word: words) {
if (list.contains(word)) {
counter++;
}
}
List<Integer> B= Arrays.asList(counter++);
}
}
}
}
}
}

Best approach: You have both the ArrayLists in main(), pass them as function parameters to functions(from any class) that need them.
Not so good approach: Store the ArrayLists as package protected static class variables in the cone and ctwo classes. You can access them as cone.A and ctwo.B.

Pass the same array list in the constructor of both the classes.

your program seems weird.
I would suggest reading words and adding distinct words to hashmap with key as word and value as it's count.

Related

StringTokenizer doesn't read the firs line of the file.txt

I'm trying to take every single words from a text file and put them into a ArrayList but the StringTokenizer doesn't read the first line of the text file... What's wrong?
public class BufferReader {
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader("C://Java-projects//EsameJava//prova.txt"));
String line = reader.readLine();
List<String> str = new ArrayList<>();
while ((line = reader.readLine()) != null) {
StringTokenizer token = new StringTokenizer(line);
while (token.hasMoreTokens()) {
str.add(token.nextToken());
}
}
System.out.println(str);
The only solution I found is to start the text file from the second line but it's not what I want...
This is how you could marry the (very) old and the new(er) to provide a collection of words:
import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WordCollector {
public static void main(String[] args) {
try {
List<String> words = WordCollector.getWords(Files.lines(Paths.get(args[0])));
System.out.println(words);
} catch (Throwable t) {
t.printStackTrace();
}
}
public static List<String> getWords(Stream<String> lines) {
List<String> result = new ArrayList<>();
BreakIterator boundary = BreakIterator.getWordInstance();
lines.forEach(line -> {
boundary.setText(line);
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
String candidate = line.substring(start, end).replaceAll("\\p{Punct}", "").trim();
if (candidate.length() > 0) {
result.add(candidate);
}
}
});
return result;
}
}

How to split file input into 2 different arrays java

How do I split a file input text into 2 different array? I want to make n array for the names, and an array for the phone numbers. I managed to do the file input, but ive tried everything and cant seem to split the names and the numbers, then put it into 2 different arrays. Im noob pls help
here is how the phonebook.txt file looks like
Bin Arry,1110001111
Alex Cadel,8943257000
Poh Caimon,3247129843
Diego Amezquita,1001010000
Tai Mai Shu,7776665555
Yo Madow,1110002233
Caup Sul,5252521551
This Guy,7776663333
Me And I,0009991221
Justin Thyme,1113332222
Hey Oh,3939399339
Free Man,4533819911
Peter Piper,6480013966
William Mulock,9059671045
below is my code
import java.io.*;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class demos {
public static void main(String[] args){
FileInputStream Phonebook;
DataInputStream In;
int i = 0;
String fileInput;
try
{
Phonebook = new FileInputStream("phonebook.txt");
FileReader fr = new FileReader("phonebook.txt");
BufferedReader br = new BufferedReader(fr);
String buffer;
String fulltext="";
while ((buffer = br.readLine()) != null) {
fulltext += buffer;
// System.out.println(buffer);
String names = buffer;
char [] Y ;
Y = names.toCharArray();
System.out.println(Y);
}}
catch (FileNotFoundException e)
{
System.out.println("Error - this file does not exist");
}
catch (IOException e)
{
System.out.println("error=" + e.toString() );
}
For a full functionnal (rather than imperative) solution I propose you this one :
public static void main(String[] args) throws IOException {
Object[] names = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[0]).toArray();
Object[] numbers = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[1]).toArray();
System.out.println("names in the file are : ");
Arrays.stream(names).forEach(System.out::println);
System.out.println("numbers in the file are : ");
Arrays.stream(numbers).forEach(System.out::println);
}
output
names in the file are :
Bin Arry
Alex Cadel
Poh Caimon
Diego Amezquita
Tai Mai Shu
Yo Madow
Caup Sul
This Guy
Me And I
Justin Thyme
Hey Oh
Free Man
Peter Piper
William Mulock
numbers in the file are :
1110001111
8943257000
3247129843
1001010000
7776665555
1110002233
5252521551
7776663333
0009991221
1113332222
3939399339
4533819911
6480013966
9059671045
As you can see functionnal programming is short and smart …. and easy when you're accustomed
You could simplify it if you are using Java 8:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
public class Test {
static ArrayList<String> names = new ArrayList<String>();
static ArrayList<String> numbers = new ArrayList<String>();
/**
* For each line, split it on the comma and send to splitNameAndNum()
*/
public static void main(String[] args) throws IOException {
Files.lines(new File("L:\\phonebook.txt").toPath())
.forEach(l -> splitNameAndNum(l.split(",")));
}
/**
* Accept an array of length 2 and put in the proper ArrayList
*/
public static void splitNameAndNum(String[] arr) {
names.add(arr[0]);
numbers.add(arr[1]);
}
}
And in Java 7:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Test {
static ArrayList<String> names = new ArrayList<String>();
static ArrayList<String> numbers = new ArrayList<String>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("L:\\phonebook.txt")));
String line;
while ((line = br.readLine()) != null) {
splitNameAndNum(line.split(","));
}
}
/**
* Accept an array of length 2 and put in the proper ArrayList
*/
public static void splitNameAndNum(String[] arr) {
names.add(arr[0]);
numbers.add(arr[1]);
}
}

Creating an Arrylist in a Arraylist in Java

This is my first post so sorry if I mess something up or if I am not clear enough. I have been looking through online forums for several hours and spend more trying to figure it out for myself.
I am reading information from a file and I need a loop that creates an ArrayList every time it goes through.
static ArrayList<String> fileToArrayList(String infoFromFile)
{
ArrayList<String> smallerArray = new ArrayList<String>();
//This ArrayList needs to be different every time so that I can add them
//all to the same ArrayList
if (infoFromFile != null)
{
String[] splitData = infoFromFile.split(":");
for (int i = 0; i < splitData.length; i++)
{
if (!(splitData[i] == null) || !(splitData[i].length() == 0))
{
smallerArray.add(splitData[i].trim());
}
}
}
The reason I need to do this is that I am creating an app for a school project that reads questions from a delimited text file. I have a loop earlier that reads one line at a time from the text. I will insert that string into this program.
How do I make the ArrayList smallerArray a separate ArrayList everytime it goes through this method?
I need this so I can have an ArrayList of each of these ArrayList
Here is a sample code of what you intend to do -
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class SimpleFileReader {
private static final String DELEMETER = ":";
private String filename = null;
public SimpleFileReader() {
super();
}
public SimpleFileReader(String filename) {
super();
setFilename(filename);
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public List<List<String>> getRowSet() throws IOException {
List<List<String>> rows = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(row -> rows.add(Arrays.asList(row.split(DELEMETER))));
}
return rows;
}
}
And, here is the JUnit test for the above code -
import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.Test;
public class SimpleFileReaderTest {
public SimpleFileReaderTest() {
super();
}
#Test
public void testFileReader() {
try {
SimpleFileReader reader = new SimpleFileReader("c:/temp/sample-input.txt");
List<List<String>> rows = reader.getRowSet();
int expectedValue = 3; // number of actual lines in the sample file
int actualValue = rows.size(); // number of rows in the list
if (actualValue != expectedValue) {
fail(String.format("Expected value for the row count is %d, whereas obtained value is %d", expectedValue, actualValue));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Array contains null values

I was trying to read some words from a text file and then arrange them into descending array.
I reached the point where I read the words successfully,stored the words in a array, and when I went ahead to arrange it into descending form I noticed that my array also contained some null values.
When I tried to remove the null values using (complete code below)
Arrays.stream(w.words).filter(x->x != null).toArray(); , it still didn't worked.
After trying for quite some time now I think I need some help here.
Code,text file and output at this stage is as follows:
`
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
public class Practise {
private Scanner fp;
private Scanner scanLine;
private String[] words = new String[6] ;
int count;
String temp;
String [][] samewords;
int size;
String[] words_sorted;
public Practise() {
openFile();
readFile();
printa();
}
private void openFile() {
try {
fp = new Scanner(new File ("D:\\workspace\\file.txt"));
}
catch (Exception e) {
System.out.println("File does not exist");
}
}
private void readFile() {
try {
count = 0;
while (fp.hasNextLine()) {
String strLine = fp.nextLine();
scanLine = new Scanner(strLine);
words[count] = scanLine.next();
System.out.println("Here2"+words[count]);
System.out.println();
count++;
}
}
catch (Exception e) {
System.err.print("Error: " + e.getMessage());
}
}
private void printa() {
try (BufferedReader br = new BufferedReader(new FileReader("D:\\workspace\\file.txt"))) {
size = findLongestWords();
samewords = new String[size][size];
String line;
int i = 0;
String [] temp;
while ((line = br.readLine()) != null) {
temp = line.split(",");
for (int j = 0; j < samewords[i].length; j++) {
samewords[i][j] = temp[j];
System.out.println(samewords[i][j]);
}
i++;
}
//System.out.println(answers[1][2]);
} catch (IOException e) {
e.printStackTrace();
}
}
public int findLongestWords() throws FileNotFoundException {
int longest_word = 0;
int current;
BufferedReader sc = new BufferedReader(new FileReader("D:\\workspace\\file.txt"));
String li;
String[] tr;
try {
while ((li = sc.readLine())!= null ) {
tr = li.split(",");
current = tr.length;
if (current > longest_word) {
longest_word = current;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\n"+longest_word+"\n");
return longest_word;
}
private String[] sort(String[] string) {
/*Local variables*/
Map<String, Integer> map=new LinkedHashMap<String, Integer>();
Map<String, Integer> mapCopy=new LinkedHashMap<String, Integer>();
int [] lengthsArray=new int[string.length];
String [] sortedStrings=new String[string.length];
int counter1=0;
int counter2=0;
/* Store all the pairs <key,value>
* i.e <string[i],string[i].length>
*/
for(String s:string) {
System.out.println(s);
map.put((String) s, s.length());
lengthsArray[counter1]= s.length();//store all the lengths
counter1++;
}
mapCopy=new LinkedHashMap<String, Integer>(map);//make a copy of map
Arrays.sort(lengthsArray);//sort the array of lengths
/*
* Sort array according to the array of lengths
* by finding the matching value from the map
* then add it to the final string array,and then remove it from the map
*/
for(int item:lengthsArray) {
for(Map.Entry<String, Integer> e:map.entrySet()) {
if(item==e.getValue()) {
sortedStrings[counter2]=e.getKey();
counter2++;
map.remove(e.getKey());
break;
}
}
}
map=mapCopy;
System.out.println(map);//print map
return sortedStrings;
}
public static void main(String[] args) {
Practise w = new Practise();
System.out.println(Arrays.toString(w.words));
w.sort(w.words);
}
}
`
file.txt is:
ACT,CAT,AT,RAT,PAT,TAT
output is:
Here2ACT,CAT,AT,RAT,PAT,TAT
6
ACT
CAT
AT
RAT
PAT
TAT
[ACT,CAT,AT,RAT,PAT,TAT, null, null, null, null, null]
ACT,CAT,AT,RAT,PAT,TAT
null
Exception in thread "main" java.lang.NullPointerException
at Practise.sort(Practise.java:190)
at Practise.main(Practise.java:239)
null is because of the word array which you have declared ( predefined size ). Probably you can change that and use ArrayList (as it can be of dynamic size) instead of an String array, which can help you resolve. Just to help you, follow below changes:
private List<String> words = new ArrayList<>();
/*update below line in readFile() instead of words[count] = scanLine.next();*/
words.add(scanLine.next());
Change method signature sort(List<String> string)
//also update below declarations
int[] lengthsArray = new int[string.size()];
String[] sortedStrings = new String[string.size()];
change Arrays.toString(w.words) to just w.words in print statement
Hope this helps. Everything looks good.

How to create a regex who verify the existence of a number into an array in java

i want to verify if a number for example 701234567 is an element of my array in java. For this, my code search if my number who is begening with 7 and have 9 digits is a element of my array "numbercall.txt" who have 5 elements. This is my text file:
numbercall.txt [ 702345678, 714326578, 701234567, 791234567,751234567]
This is my code:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestNumberLt {
static String[] arr= null;
String filename = "fichiers/numbercall.txt";
static String a = null ;
static List<String> list = new ArrayList<String>();
public static void main(String [] args) throws IOException{
FileInputStream fstream_school = new FileInputStream(filename);
DataInputStream data_input = new DataInputStream(fstream_school);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String str_line;
while ((str_line = buffer.readLine()) != null)
{
str_line = str_line.trim();
if ((str_line.length()!=0))
{
list.add(str_line);
}
}
int b = 773214576;
//convert the arraylist to a array
arr = (String[])list.toArray(new String[list.size()]);
Pattern p = Pattern.compile("^7[0|6|7][0-9]{7}$");
Matcher m ;
//a loop for verify if a number exist in this array
for (int j = 0; j < list.size();)
{
System.out.print(" "+list.get(j)+ " ");
m = p.matcher(list.get(j));
/*while(m.find())
System.out.println(m.group());*/
if(list.get(j).equals(b))
{
System.out.println("Trouvé "+list.get(j));
break;
}
else
{
System.out.println("ce numéro ("+b+") n'existe pas!");
}
break;
}
}
}
Do it simply like this
String str_line= "702345678,714326578,701234567,791234567,751234567";
String[] strArray = str_line.split(",");
String key = "702345678";
for(String v:strArray) {
if(v.equals(key)) {
System.out.println("found");
}
}
I'm not realy sure of what you want, but if you just need the index of b in your array just do this:
public static void main(String [] args) throws IOException{
...
int b = 773214576;
int tmp = list.indexOf(b+"");
if(tmp!=-1) {
System.out.println("Trouvé "+ b + " à l'index " + tmp);
} else {
System.out.println("Ce numéro ("+b+") n'existe pas!");
}
...
}
Another answer, using Guava :
(in this case, there really is no need, you could simply use split() method from String object, but like Guava readibility and returns)
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.common.base.Splitter;
public class RegexExample {
String filename = "numbercall.txt";
public boolean isInList(String numberToCheck) throws IOException {
BufferedReader file = loadFile();
for (String number : extractNumberListFrom(file)) {
if (number.trim().equals(numberToCheck)) {
return true;
}
}
return false;
}
private Iterable<String> extractNumberListFrom(BufferedReader buffer) throws IOException {
StringBuilder numberList = new StringBuilder();
String line;
while ((line = buffer.readLine()) != null) {
numberList.append(line);
}
return Splitter.on(",").split(numberList.toString());
}
private BufferedReader loadFile() {
InputStream fstream_school = RegexExample.class.getResourceAsStream(filename);
BufferedReader buffer = new BufferedReader(new InputStreamReader(fstream_school));
return buffer;
}
}

Categories