I have the following code with an ArrayList that is filled in other Java class that is a Thread (this is always filled, I have checked every time), then I have in the Main class the problematic block while(true) and the issue is that never ends if I comment or delete the line System.out.println(IDS.size());
Although are Threads in charge of complete the information I need, I cant show the results until all of them are finished. This is the reason of while(true) block.
public static ArrayList<String> IDS = new ArrayList<String>();
//this arraylist is filled in other classes correctly (each Thread add a element -> 10 in total)
//here is the problem
while (true) {
//if I comment the next system.out.println line
//the loop never ends and never breaks
System.out.println(IDS.size());
if(IDS.size()==10) {
break;
}
}
//when the array is filled with the 10 elements, I show all the info
for (int k = 0; k < impresoras.size(); k++) {
System.out.println(impresoras.get(k).ID);
}
I donĀ“t know why this is happening, can someone helps?
Thanks in advance.
Finally I use the join methods for the Threads to avoid the while true loop.
So only I have to call the next method and then do the System.out.println of my items, that will be printed when all Threads ends their work.
public static ArrayList<MyThread> threadList = new ArrayList<MyThread>();
public static void openFileAndCreateThreads(String fileName) {
String line = null;
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] line_parts = line.split(";");
MyThread t= new MyThread(line_parts[0].trim(), line_parts[1], line_parts[2]);
threadList.add(t);
t.start();
}
for (int j=0;j<threadList.size();j++) {
try {
threadList.get(j).join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (Exception ex) {
}
}
}
Related
I wrote a program to accept input from a text file, and display the words from the file in ascending order with no duplicates. The output is correct if there is no exception thrown. If the exception is thrown, the user is asked for valid input and the initial method is repeated. When this happens, and a valid input is finally entered, the output is duplicated.
I know something is not being reset, but I cannot figure out what it is.
public void go() {
getWords();
System.out.println(wordList);
wordList = new ArrayList<String>(new HashSet<String>(wordList));
Collections.sort(wordList);
System.out.println(wordList);
}
void getWords() {
try {
File file = new File(getInput());
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
addWord(line);
}
} catch(Exception ex) {
System.out.println("Invalid file name, try again.");
go();
}
}
void addWord(String lineToParse) {
String[] tokens = lineToParse.split("\\s");
for(int i = 0; i < tokens.length; i++) {
wordList.add(tokens[i]);
}
}
When you call go() from the catch block, you're forgetting that the original go() invocation is still on the stack. It doesn't disappear just because you've called the method again. Essentially, you're performing some accidental recursion.
So in this case, you'll call go() a second time, it will execute as per normal, then the stack will "unwind" and execute the remainder of the first invocation of the go method, printing out the wordlist, sorting it, then printing it out again.
A quick fix might be to have getWords() return a boolean (false if an exception is thrown), then just change the first line to while(!getWords());.
It's because you are calling go, method inside the catch block which cause printing of the output again, you could correct it like this,
public void go() {
getWords();
System.out.println(wordList);
wordList = new ArrayList<String>(new HashSet<String>(wordList));
Collections.sort(wordList);
System.out.println(wordList);
}
void getWords() {
try {
File file = new File(getInput());
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
addWord(line);
}
} catch(Exception ex) {
System.out.println("Invalid file name, try again.");
getwords(); //Changed
}
}
void addWord(String lineToParse) {
String[] tokens = lineToParse.split("\\s");
for(int i = 0; i < tokens.length; i++) {
wordList.add(tokens[i]);
}
}
I am trying to read from 45 pages that are all the same (except for the part im reading of course) and write them in a list of line lists.
I wrote this code so far:
public static ArrayList<ArrayList<String>> linesWeNeed(){
ArrayList<ArrayList<String>> returnListList = new ArrayList<ArrayList<String>>();
for(int i = 1; i<=45; i++){
int pageNum=(i*20)-20;
System.out.println("PageNum"+pageNum);
URL url=null;
try {
url = new URL("http://tq.mot.gov.il/index.php?option=com_moofaq&iotype=w&view=category&lang_ovrrde=ENG&id=3&Itemid=29&limitstart="+pageNum);
} catch (MalformedURLException e) {
System.out.println("Oh uh!");
}
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
} catch (IOException e) {
System.out.println("FATAL ERROR");
e.printStackTrace();
}
ArrayList<String> lineCodes = new ArrayList<String>();
ArrayList<String> linesWeNeed = new ArrayList<String>();
String line;
try {
readLines:
while((line=in.readLine())!=null){
if(line.contains("</tr></table></div></div></li></ul></div></div><br /></div>")){
break readLines;
}
lineCodes.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int o = 1; o>=lineCodes.size(); o++){
String readLine = lineCodes.get(o-1);
if(o>=297){
linesWeNeed.add(readLine);
}
}
returnListList.add(linesWeNeed);
}
return returnListList;
}
There are no errors, but for some reason every list in the arraylist the methods return is empty. Why?
Thanks in advance!
for(int o = 1; o>=lineCodes.size(); o++){
Your loop condition is back to front. Try <=.
for(int o = 1; o>=lineCodes.size(); o++){
Double-check the loop condition there; seems like that block is never going to execute...
I cant figure out how to loop through this instead of just repeating the code, bugging the hell outta me! FYI assignment has already been turned in using 5 iterations of code, just wanted to learn how to implement the string array holding file contents into a for loop for future knowledge. I have tried for a few hours but it just prints the filename, cant seem to get the file contents.
/*************************************************************************
* LinuxSys.java
*
* This program reads text from a file
**************************************************************************/
import java.util.*;
import java.io.*;
public class LinuxSys {
public static void main (String[] args) {
String systemInfo[] = new String [5];
int i = 0;
// using _ to simulate file paths to test on local cpu, as it is easier/quicker
// than logging onto server/copy pasting code into new pico file
systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
systemInfo[1] = "_proc_meminfo.txt"; //local files
systemInfo[2] = "_proc_version.txt"; //local files
systemInfo[3] = "_proc_sys_kernel_hostname.txt"; //local files
//systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
// 1st try to print server host name file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 2nd try to print server memory file
{
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 3rd try to print version file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++;
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
} // end main
} // end class
for(int i=0; i < systemInfo.size; ++i)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
while(i < systemInfo.size)
{
// the code you want to repeat with i varying each time
++i;
}
or
int i=0;
while(i++ < systemInfo.size)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
do
{
// the code you want to repeat with i varying each time
}
while(++i < systemInfo.size)
or...
I have struggled a long time to get the try-catch-finally block to work. I'm a beginner in java, and are currently learning how to read/write/handle exceptions. In my task I'm trying to read from two separate .txt files. One has countries and population, the other has countries and the area of the country. This is further printed out to a new file where information about countries and area per person is displayed.
I'm not sure if I really can put the finally inside a try-catch block.
Currently I'm getting the error message "Unhandled FileNotFoundException etc.". I've been trying this for for a long time now, and just can't get it to work properly.
private String country;
private double value;
Scanner in1 = new Scanner(new File("countryPopulation.txt"));
Scanner in2 = new Scanner(new File("countryArea.txt"));
PrintWriter out = new PrintWriter("countryAreaPerInhabitant");
public IOAndExceptionHandling(String line) {
int i = 0;
while (!Character.isDigit(line.charAt(i))) {
i++;
}
this.country = line.substring(0, i - 1).trim();
this.value = Double.parseDouble(line.substring(i).trim());
}
public String getCountry() {
return this.country;
}
public double getValue() {
return this.value;
}
public void printAreaPerPerson() {
try {
try {
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
}
finally {
in1.close();
in2.close();
out.close();
}
}
catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
}
catch (IOException e) {
e.printStackTrace();
}
}
Thanks! :)
The finally block goes after the catch blocks. It will execute regardless of an exception being thrown or successful completion of the block.
Scanner in1; //field declaration with no assignment
Scanner in2; //field declaration with no assignmetn
/* Omitted Class declaration & other code */
try {
in1 = new Scanner(new File("countryPopulation.txt")); //these require FNF to be caught
in2 = new Scanner(new File("countryArea.txt"));
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(
in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(
in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
} catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
} catch (IOException e) {
e.printStackTrace();
} finally {
in1.close();
in2.close();
out.close();
}
The first rendition of this code was throwing the unhandled exception error because the inner try block did not catch the FileNotFoundException. Even though you had a try...catch wrapping that try block, which did catch the FileNotFoundException, the exception would not propogate upwards through the nested try..catch statements
You are nesting two try catch blocks. The inner one only has try finally, but no catch statements. That's where the FileNotFoundException would occur.
try {
try {
Either remove the outer block and just use one or move the catch statements inside the inner try finally.
Copy paste this
public void printAreaPerPerson() {
try {
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue() / country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
} catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
} catch (IOException e) {
e.printStackTrace();
} finally {
in1.close();
in2.close();
out.close();
}
}
Put the finally block out side of your try block.
You don't need the inner try block.
In Java, here is the code to read a file with a table of integers:
public static int[][] getDataset() {
// open data file to read n and m size parameters
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
// count the number of lines
int i = -1;
String line = null, firstLine = null;
do {
// read line
try {
line = br.readLine();
i++;
if (i == 0) firstLine = line;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
} while (line != null);
// close data file
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// check the data for emptiness
if (i == 0) {
System.out.println("The dataset is empty!");
System.exit(1);
}
// initialize n and m (at least the first line exists)
n = i; m = firstLine.split(" ").length;
firstLine = null;
// open data file to read the dataset
br = null;
try {
br = new BufferedReader(new FileReader(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
// initialize dataset
int[][] X = new int[n][m];
// process data
i = -1;
while (true) {
// read line
try {
line = br.readLine();
i++;
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// exit point
if (line == null) break;
// convert a line (string of integers) into a dataset row
String[] stringList = line.split(" ");
for (int j = 0; j < m; j++) {
X[i][j] = Integer.parseInt(stringList[j]);
}
}
// close data file
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return X;
}
Dataset size parameters n and m are of type static final int and declared outside as well as static final String filePath.
I give you my solution (maybe will be useful for newbies later coming to read this) and ask if it is possible to make it faster in time and/or consuming less memory? I'm interested in perfect micro-optimization, any advice would be great here. In particular I do not like the way the file is opened twice.
Read the file only once and add all lines to an ArraList<String>.
ArrayList grows automatically.
Later process that ArrayList to split the lines.
Further optimisations:
Strimg.split uses a huge regular expression analyzer. Try it with StringTokenizer or your own stringsplit method.
Instead of ArrayList you could avoid overhead by using GrowingIntArray,or GrowingStringArray, these avoid some overhead but are less handy.
speed and mempory usage are contradicting, often you cannot optimize both.
You can save memor by using a one dimesnional array, in java 2d arrays need more space becauseeach column is an object.
access one dim array by X[col + row *rowsize].