Looking for some critique for this code. but ultimately I would like to be directed to resources/books that address my code writing weaknesses, in terms of style structure an convention :
The task is to create code that would read a file that has several questions and answers, each question starts with the word "Question", and out put the question and a number of lines from the answer that is not greater than 40 lines.
my code method below is meant to:
read all lines into an List.
select a random start line in the list.
check id the line starting with the string "Question".
check if the remaining list elements are more than 40 (I've appended 40 empty lines to the end of the file, to make sure to include the last lines of the file).
create a string buffer to include maximum the 39 lines which are present after the start line, the one that contains "Question" , if the the word "Question" appears before the 40th line, then we we end the text captured at the preceding line (creating a text block).
return that (text block).
public static String readJavaInterview() throws IOException{
List<String> list = Files.readAllLines(new File("src/lists/JavaCodingInterview.txt").toPath(), Charset.defaultCharset() );
List<String> subList = new ArrayList<>();
int start=0 , end= 0;
Random rand = new Random();
int n = rand.nextInt(list.size());
StringBuffer textBlock= new StringBuffer();
Pattern p = Pattern.compile("Question");
Matcher m;
textBlock.append("Some Java Interview Qs :\n");
if (n + 40 < list.size()){
subList = list.subList(n, n + 40);
for (int i = 0 ; i < subList.size() - 1 ; i++){
m = p.matcher(subList.get(i).toString());
boolean b = m.find();
if (b)
{
start= i + 1;
textBlock.append(subList.get(i) + "\n");
break;
}else{
continue;
}
}
for(int j = start ; j < start + 39; j++){
m = p.matcher(subList.get(j).toString());
boolean b = m.find();
if (!b){
textBlock.append(subList.get(j) + "\n");
}else{
break;
}
}
}else{
return "";
}
return textBlock.toString();
}
Would this be how you would do it?