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.
Related
I'm working on two word document comparison manually where i should not miss any Strings, Special chars, space and all the stuff and that document is around 150 pages or more. so its very headache to do comparison. Then I have written small java program to compare two documents but I'm not able to list the missing words.
Using Apche POI Library
Thanks in advance.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class ReadDocFile {
private static XWPFDocument docx;
// private static String path = "C:\\States wise\\NH\\Assessment
// 2nd\\test.docx";
private static ArrayList<String> firstList = new ArrayList<String>(); // refers to first document list
private static ArrayList<String> secondList = new ArrayList<String>(); // refers to second document list
private static List<XWPFParagraph> paragraphList;
private static Map<String, String> map = null;
private static LinkedHashSet<String> firstMissedArray = new LinkedHashSet<String>(); // refers to first document Linked hash set
private static LinkedHashSet<String> secondMissedArray = new LinkedHashSet<String>(); // refers to second document Linked hash set
public static void getFilePath(String path) {
FileInputStream fis;
try {
fis = new FileInputStream(path);
docx = new XWPFDocument(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void get_First_Doc_Data() {
getFilePath("C:\\States wise\\NH\\Assessment 2nd\\test.docx");
paragraphList = docx.getParagraphs();
System.out.println("******************** first list Starts here ******************** ");
System.out.println();
for (int i = 0; i < paragraphList.size() - 1; i++) {
firstList.add(paragraphList.get(i).getText().toString());
System.out.println(firstList.get(i).toString());
}
System.out.println("*********** first list Ends here ********************");
}
public static void get_Second_Doc_Data() {
getFilePath("C:\\States wise\\NH\\Assessment 2nd\\test1.docx");
paragraphList = docx.getParagraphs();
System.out.println("******************** Second list Starts here ******************** ");
System.out.println();
for (int i = 0; i < paragraphList.size() - 1; i++) {
secondList.add(paragraphList.get(i).getText().toString());
System.out.println(secondList.get(i).toString());
}
System.out.println("*********** Second list Ends here ********************");
}
public static void main(String[] args) {
get_First_Doc_Data();
get_Second_Doc_Data();
//System.out.println("First Para: " + firstList.contains(secondList));
compare();
compare_Two_List();
}
private static void compare() {
String firstMiss = null;
//String secondMiss = null;
for (int i = 0; i < firstList.size(); i++) {
for (int j = 0; j < secondList.size(); j++) {
if (!firstList.get(i).toString().equals(secondList.get(i).toString())) {
firstMiss = firstList.get(i).toString();
//secondMiss = secondList.get(i).toString();
map = new HashMap<String, String>();
}
}
firstMissedArray.add(firstMiss);
//secondMissedArray.add(secondMiss);
// System.out.println(missedArray.get(i).toString());
}
}
private static void compare_Two_List() {
int num = 0;
map.clear();
Iterator<String> first = firstMissedArray.iterator();
//Iterator<String> second = secondMissedArray.iterator();
while (first.hasNext()) {
map.put(""+num, first.next());
num++;
}
System.out.println(firstMissedArray.size());
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
// it.remove(); // avoids a ConcurrentModificationException
}
}
}
I have taken liberty to modify your code to arrive at the solution for your problem. Please go through this.
This should pretty much solve your problem - put SYSO statements wherever you think is necessary and tweak the flow of the program to achieve desired checks as per you requirement. In my hurry, I may not have made use of coding standards of using try catch block for error handling and handling the negative scenarios, so please take care of that when implementing it live.
In case if the documents are not .DOCX but .PDF make use of the Apache PDFBox api.
Here is the Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
public class Comapre_Docs {
private static final String FIRST_DOC_PATH = "E:\\Workspace_Luna\\assignments\\Expected.docx";
private static final String SECOND_DOC_PATH = "E:\\Workspace_Luna\\assignments\\Actual.docx";
private static XWPFDocument docx;
private static List<XWPFParagraph> paragraphList;
private static ArrayList<String> firstList = new ArrayList<String>();
private static ArrayList<String> secondList = new ArrayList<String>();
public static void get_Doc_Data(String filePath, ArrayList listName)
throws IOException {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
docx = new XWPFDocument(fis);
paragraphList = docx.getParagraphs();
for (int i = 0; i <= paragraphList.size() - 1; i++) {
listName.add(paragraphList.get(i).getText().toString());
}
fis.close();
}
public static void main(String[] args) throws IOException {
get_Doc_Data(FIRST_DOC_PATH, firstList);
get_Doc_Data(SECOND_DOC_PATH, secondList);
compare(firstList, secondList);
}
private static void compare(ArrayList<String> firstList_1,
ArrayList<String> secondList_1) {
simpleCheck(firstList_1, secondList_1);
int size = firstList_1.size();
for (int i = 0; i < size; i++) {
paragraphCheck(firstList_1.get(i).toString().split(" "),
secondList_1.get(i).toString().split(" "), i);
}
}
private static void paragraphCheck(String[] firstParaArray,
String[] secondParaArray, int paraNumber) {
System.out
.println("=============================================================");
System.out.println("Paragraph No." + (paraNumber + 1) + ": Started");
if (firstParaArray.length != secondParaArray.length) {
System.out.println("There is mismatch of "
+ Math.abs(firstParaArray.length - secondParaArray.length)
+ " words in this paragraph");
}
TreeMap<String, Integer> firstDocPara = getOccurence(firstParaArray);
TreeMap<String, Integer> secondDocPara = getOccurence(secondParaArray);
ArrayList<String> keyData = new ArrayList<String>(firstDocPara.keySet());
for (int i = 0; i < keyData.size(); i++) {
if (firstDocPara.get(keyData.get(i)) != secondDocPara.get(keyData
.get(i))) {
System.out
.println("The following word is missing in actual document : "
+ keyData.get(i));
}
}
System.out.println("Paragraph No." + (paraNumber + 1) + ": Done");
System.out
.println("=============================================================");
}
private static TreeMap<String, Integer> getOccurence(String[] paraArray) {
TreeMap<String, Integer> paragraphStringCountHolder = new TreeMap<String, Integer>();
paragraphStringCountHolder.clear();
for (String a : paraArray) {
int count = 1;
if (paragraphStringCountHolder.containsKey(a)) {
count = paragraphStringCountHolder.get(a) + 1;
paragraphStringCountHolder.put(a, count);
} else {
paragraphStringCountHolder.put(a, count);
}
}
return paragraphStringCountHolder;
}
private static boolean simpleCheck(ArrayList<String> firstList,
ArrayList<String> secondList) {
boolean flag = false;
if (firstList.size() > secondList.size()) {
System.out
.println("There are more paragraph in Expected document than in Actual document");
} else if (firstList.size() < secondList.size()) {
System.out
.println("There are more paragraph in Actual document than in Expected document");
} else if (firstList.size() == secondList.size()) {
System.out.println("The paragraph count in both documents match");
flag = true;
}
return flag;
}
}
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();
}
}
}
I have two arraylists
arraylist dName has values:
mark, 22
peter, 34
ken, 55
arraylist dest has values:
mark, London
peter, Bristol
mark, Cambridge
I want to join merge them so that their output gives:
mark
London
Cambridge
peter
Bristol
Ken
this is the code i have for now, i'm not really usre how to split on the comma and search the other array
public class Sample {
BufferedReader br;
BufferedReader br2;
public Sample() {
ArrayList<String> dName = new ArrayList<String>();
ArrayList<String> dest = new ArrayList<String>();
String line = null;
String lines = null;
try {
br = new BufferedReader(new FileReader("taxi_details.txt"));
br2 = new BufferedReader(new FileReader("2017_journeys.txt"));
while ((line = br.readLine()) != null &&
(lines = br2.readLine()) != null){
String name [] = line.split(";");
String destination [] = lines.split(",");
// add values to ArrayList
dName.add(line);
dest.add(lines);
// iterate through destination
for (String str : destination) {
}
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
}
}
Now, I'm not sure whether this is the proper way, but at least it is working.
taxi_details.txt
mark, 22
peter, 34
ken, 55
2017_journeys.txt
mark, London
peter, Bristol
mark, Cambridge
FileReader
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Collectors;
public class FileReader {
public List<String> read(String fileName) throws IOException{
return Files.lines(new File(fileName).toPath()).collect(Collectors.toList());
}
}
This class lets you avoid all the messy try-catch blocks.
Line
public class Line{
public static final String DELIMITER = ",";
public static final int INDEX_NAME = 0;
public static final int INDEX_VALUE = 1;
private String line;
private String[] values;
public Line(String line) {
this.line = line;
this.values = line.split(DELIMITER);
}
public String getName(){
return this.values[INDEX_NAME];
}
public String getValue(){
return this.values[INDEX_VALUE];
}
public void emptyValue(){
this.values[INDEX_VALUE] = "";
}
#Override
public String toString() {
return this.line;
}
}
This class has the mere prupose of preparing the data as needed for merging.
Main
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader();
// Read lines
List<String> dName = fileReader.read("taxi_details.txt");
List<String> dest = fileReader.read("2017_journeys.txt");
// Convert into proper format
List<Line> dNameLines = dName.stream().map(Line::new).collect(Collectors.toList());
List<Line> destLines = dest.stream().map(Line::new).collect(Collectors.toList());
// Remove ID
dNameLines.forEach(Line::emptyValue);
// Merge lists
Map<String, String> joined = join(dNameLines, destLines);
// Print
for (Entry<String, String> line: joined.entrySet()) {
System.out.println(line.getKey() + " --> " + line.getValue());
}
}
public static Map<String, String> join(List<Line> a, List<Line> b){
Map<String, String> joined = new HashMap<>();
// Put first list into map, as there is no danger of overwriting existing values
a.forEach(line -> {
joined.put(line.getName(), line.getValue());
});
// Put second list into map, but check for existing keys
b.forEach(line -> {
String key = line.getName();
if(joined.containsKey(key)){ // Actual merge
String existingValue = joined.get(key);
String newValue = line.getValue();
if(!existingValue.isEmpty()){
newValue = existingValue + Line.DELIMITER + newValue;
}
joined.put(key, newValue);
}else{ // Add entry normally
joined.put(line.getName(), line.getValue());
}
});
return joined;
}
}
You might want to move the join method into its own class.
Output
peter --> Bristol
ken -->
mark --> London, Cambridge
You should iterate on array B.
For each string, split on the comma and search in A for a string that starts with the first part of the split.
Then append the second part of the split to the entry found in A.
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.
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;
}
}