Java binary search array list - java

I'm trying to search for strings in an array list as below which is working fine. But, the challenge is when the string i'm searching for is embedded in between some text example "XXXXTESTXXXX".
The binary search what i have so far seems to not find it. I have also tried "contains" method but didn't work either. Not sure where i'm i going wrong. Please suggest.
Array Content :[PIGEON, XXXBEARXXX , XXXCAT, XXXDOG, XXXELEPHANTXXX , XXXHORSEXXX , XXXLIONXXX , XXXMOUSEXXX , XXXOWLXXX , XXXPARROTXXX , XXXTIGERXXX ]
Example search string:-
Search String = "BEAR"
Code
ArrayList File_F1_Array = new ArrayList();
// Read the lines of the Source file (File_1) in to Arraylist
try {
BufferedReader File_F1_Br = new BufferedReader (new FileReader(File_F1));
while ((File_F1_Line = File_F1_Br.readLine()) !=null ) {
File_F1_Array.add(File_F1_Line);
}
File_F1_Br.close();
} catch (Exception e) {
e.printStackTrace();
}
// Sort the array list
Collections.sort(File_F1_Array);
// Search lines from Refernce file (File_2) in Arraylist
try {
BufferedReader File_F2_br = new BufferedReader (new FileReader(File_F2));
while ((File_F2_Line = File_F2_br.readLine()) !=null) {
int index = Collections.binarySearch(File_F1_Array, File_F2_Line);
boolean StringCheck = File_F1_Array.contains(File_F2_Line);
}

your algorithm is not correct! you are searching in array which has "xx..." and you want to get rid of "xx..."s! you have to create another arraylist without "xx.." and put some binding key between 2 arrays in order to keep the first array with Xs.

Related

How can I print 2 arrays with different values in java?

I am trying to print 2 different arrays, One array has the name of the file and the other array has the content of the csv file.
First I am reading the contents of the given file through the path and then putting the content of the .csv file into an array which is nextLine[]
public static void fileRead(File file) throws IOException, CsvException {
CSVReader csvReader = new CSVReaderBuilder(new FileReader(file)).withSkipLines(1).build();
String[] nextLine;
File folder = new File("src/main/resources/FolderDocumentsToRead");
String[] fileList = folder.list();
while((nextLine = csvReader.readNext())!=null){
System.out.println("Name of file: "+fileList[0]+", Title of Text: "+nextLine[0]);
}
}
}
The output I am trying to get is meant to look like;
Name of file: ATale.csv, Title of Text: A TALE OF THE RAGGED MOUNTAINS
Name of file: Diggling.csv, Title of Text: DIDDLING
The output I am getting looks like;
Name of file: ATale.csv, Title of Text: A TALE OF THE RAGGED MOUNTAINS
Name of file: ATale.csv, Title of Text: DIDDLING
I have tried using loops to get to the correct solution but I was just getting errors thrown at me and having a hard time with them.
I'm fairly new to using arrays and java in general, any tips would be appreciated even a tip towards getting the solution.
P.S first time using Stack overflow ahaha
Before the while loop, if you create a variable to keep track of the selected index then you will be able to modify it and have the change stay after the loop has finished.
int index = 0;
while(csvReader.hasNext())
{
String fileName = fileList[index];
String title = nextLine[index];
index++;
...
}
The line
while((nextLine = csvReader.readNext())!=null)
can be/should be rewritten like so:
while(csvReader.hasNext())
{
nextLine = csvReader.readNext();
...
}
This helps a lot with reading/debugging
NOTE this is not any sort of solution but a recommendation for ease-of-use

How can you read a boolean array?

I have this boolean array that I am using in my app, but I have no idea how to save this array that I am using. Here is how I am saving the array:
public void writeArraytofile() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("array.txt", Context.MODE_PRIVATE));
for (int i = 0; i < array.length; i++) {
outputStreamWriter.write(array[i] + "");
}
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (IOException e) {
Log.v("MyActivity", e.toString());
}
}
I have searched everywhere on how to read this array and access it after the user restarts the app. And one of the things that I would not like to use is Sharedpreferences because when I uninstall my application when using the Sharedpreferences after I reinstall, it doesn't work anymore. So anything without the use of Sharedpreferences would be awesome.
Please and Thank you.
You could write as boolean + "," and when reading String[] xyz = read.split(",") and loop through that to reintialize the boolean array.
I can't say this is the most efficient, but its the only thing that comes to mind.
A simple way to save data in file with stream :
Make a class (for example mydata) and implement Serializable . Make property in this class ArrayList array .
Now you can write your object with type mydata to file, and read with streamereader easily. When you read the file, stream reader load your object and you can use the array property .
Reguards
A.Ayati

Android How can i easily read and add to the List data from txt file?

My code: https://pastebin.com/KudWYD8W
I don't know how write method loadData.
I wanna have list with only names of Games and when I press on the element should show the details.
My file looks like:
Witcher
1996
free
66h
Please help. I tried in many ways but there was always something wrong.
Try this.
1.Save the string to be read as different list item separated with a comma(,).
2.Call this method to get the list by passing the file path.
private List<String> populateAutoComplete(String path)
{
try
{
String content = readFile(path);
Log.d(TAG,
"populateAutoComplete: " + content);
List<String> listToPopulate = Arrays.asList(content.split("\\s*,\\s*"));
return listToPopulate;
}
catch (IOException e)
{
e.printStackTrace();
return Collections.emptyList();
}
}
Ask in case of any doubts. Cheers :)

ArrayList<String> in PDF from a new row

I want to send some survey in PDF from java, I tryed different methods. I use with StringBuffer and without, but always see text in PDF in one row.
public void writePdf(OutputStream outputStream) throws Exception {
Paragraph paragraph = new Paragraph();
Document document = new Document();
PdfWriter.getInstance(document, outputStream);
document.open();
document.addTitle("Survey PDF");
ArrayList nameArrays = new ArrayList();
StringBuffer sb = new StringBuffer();
int i = -1;
for (String properties : textService.getAnswer()) {
nameArrays.add(properties);
i++;
}
for (int a= 0; a<=i; a++){
System.out.println("nameArrays.get(a) -"+nameArrays.get(a));
sb.append(nameArrays.get(a));
}
paragraph.add(sb.toString());
document.add(paragraph);
document.close();
}
textService.getAnswer() this - ArrayList<String>
Could you please advise how to separate the text in order each new sentence will be starting from new row?
Now I see like this:
You forgot the newline character \n and your code seems a bit overcomplicated.
Try this:
StringBuffer sb = new StringBuffer();
for (String property : textService.getAnswer()) {
sb.append(property);
sb.append('\n');
}
What about:
nameArrays.add(properties+"\n");
You might be able to fix that by simply appending "\n" to the strings that you collecting in your list; but I think: that very much depends on the PDF library you are using.
You see, "newlines" or "paragraphs" are to a certain degree about formatting. It seems like a conceptual problem to add that "formatting" information to the data that you are processing.
Meaning: you might want to check if your library allows you to provide strings - and then have the library do the formatting for you!
In other words: instead of giving strings with newlines; you should check if you can keep using strings without newlines, but if there is way to have the PDF library add line breaks were appropriate.
Side note on code quality: you are using raw types:
ArrayList nameArrays = new ArrayList();
should better be
ArrayList<String> names = new ArrayList<>();
[ I also changed the name - there is no point in putting the type of a collection into the variable name! ]
This method is for save values in array list into a pdf document. In the mfilePath variable "/" in here you can give folder name. As a example "/example/".
and also for mFileName variable you can use name. I give the date and time that document will created. don't give static name other vice your values are overriding in same pdf.
private void savePDF()
{
com.itextpdf.text.Document mDoc = new com.itextpdf.text.Document();
String mFileName = new SimpleDateFormat("YYYY-MM-DD-HH-MM-SS", Locale.getDefault()).format(System.currentTimeMillis());
String mFilePath = Environment.getExternalStorageDirectory() + "/" + mFileName + ".pdf";
try
{
PdfWriter.getInstance(mDoc, new FileOutputStream(mFilePath));
mDoc.open();
for(int d = 0; d < g; d++)
{
String mtext = answers.get(d);
mDoc.add(new Paragraph(mtext));
}
mDoc.close();
}
catch (Exception e)
{
}
}

Search Box for Jpanel

I am in the middle of creating an app that allows users to apply for job positions and upload their CVs. I`m currently stuck on trying to make a search box for the admin to be able to search for Keywords. The app will than look through all the CVs and if it finds such keywords it will show up a list of Cvs that contain the keyword. I am fairly new to Gui design and app creation so not sure how to go about doing it. I wish to have it done via java and am using the Eclipse Window builder to help me design it. Any help will be greatly appreciated, hints, advice anything. Thank You.
Well, this not right design approach as real time search of words in all files of given folder will be slow and not sustainable in long run. Ideally you should have indexed all CV's for keywords. The search should run on index and then get the associated CV for that index ( think of indexes similar to tags). There are many options for indexing - simples DB indexing or using Apache Lucene or follow these steps to create a index using Maps and refer this index for search.
Create a map Map<String, List<File>> for keeping the association of
keywords to files
iterate through all files, and for each word in
each file, add that file to the list corresponding to that word in
your index map
here is the java code which will work for you but I would still suggest to change your design approach and use indexes.
File dir = new File("Folder for CV's");
if(dir.exists())
{
Pattern p = Pattern.compile("Java");
ArrayList<String> list = new ArrayList<String>(); // list of CV's
for(File f : dir.listFiles())
{
if(!f.isFile()) continue;
try
{
FileInputStream fis = new FileInputStream(f);
byte[] data = new byte[fis.available()];
fis.read(data);
String text = new String(data);
Matcher m = p.matcher(text);
if(m.find())
{
list.add(f.getName()); // add file to found-keyword list.
}
fis.close();
}
catch(Exception e)
{
System.out.print("\n\t Error processing file : "+f.getName());
}
}
System.out.print("\n\t List : "+list); // list of files containing keyword.
} // IF directory exists then only process.
else
{
System.out.print("\n Directory doesn't exist.");
}
Here you get the files list to show now for "Java". As I said use indexes :)
Thanks for taking your time to look into my problem.
I have actually come up with a solution of my own. It is probably very amateur like but it works for me.
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
list.clear();
String s = SearchBox.getText();
int i = 0,present = 0;
int id;
try
{
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM javaapp.test");
while(res.next())
{
i = 0;
present = 0;
while(i < 9)
{
String out = res.getString(search[i]);
if(out.toLowerCase().contains(s.toLowerCase()))
{
present = 1;
break;
}
i++;
}
if(tglbtnNormalshortlist.isSelected())
{
if(present == 1 && res.getInt("Shortlist") == 1)
{
id = res.getInt("Candidate");
String print = res.getString("Name");
list.addElement(print+" "+id);
}
}
else
{
if(present == 1 && res.getInt("Shortlist") == 0)
{
id = res.getInt("Candidate");
String print = res.getString("Name");
list.addElement(print+" "+id);
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});

Categories

Resources