Program does not run continuously - java

I'm writing a ChatBot program where, if the ChatBot doesn't have information to answer a question by the user, it asks the user how to answer the question, and then stores it in a txt file. Later, when another question is asked, the information is retrieved from the txt file and the whole thing starts over (or at least is supposed to).
The program works, however, after one query from the user, and I press enter again for a second try, nothing happens anymore.
Here is my code:
import java.io.*;
import java.util.*;
import java.nio.file.*;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]) {
System.out.println("Bot: Hello!! My name's HiBot! What's up?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
if (response.toLowerCase().contains("bye") || response.toLowerCase().contains("see ya")
|| response.toLowerCase().contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
}
processor(response);
}
public static void processor(String reply) {
try {
BufferedReader reader = new BufferedReader(new FileReader("convos.txt"));
int count = 0;
try {
String line = reader.readLine();
while (line != null) {
count++;
if (line.toLowerCase().contains(reply.toLowerCase())) {
try (Stream<String> lines = Files.lines(Paths.get("convos.txt"))) {
line = lines.skip(count).findFirst().get();
System.out.println("Bot: " + line);
recur();
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
}
reader.close();
return;
}
reader.close();
}
System.out.println("Bot: Sorry, I'm dumb. How should I reply?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
teach(reply, response);
recur();
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void teach(String context, String reply) {
try {
try {
FileWriter learn = new FileWriter("convos.txt", true);
PrintWriter out = new PrintWriter(learn);
out.println(context + "\n" + reply);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
}
System.out.println("Bot: Thank you for teaching me!! I'm smarter now!");
}
public static void recur() {
int trickLoop = 1;
while (trickLoop > 0) {
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
if (response.toLowerCase().contains("bye") || response.toLowerCase().contains("see ya")
|| response.toLowerCase().contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
System.exit(0);
}
processor(response);
}
}
}
I also think that there's definitely a better way to write the code. Does anyone have any suggestions?
EDIT: I have convos.txt but I didn't show it here.

Issue1 :
Initially file doesn't exist and you are not creating it. so it gave following error
Bot: Hello!! My name's HiBot! What's up?
You: hi
java.io.FileNotFoundException: convos.txt (The system cannot find the file specified)
Issue 2 :
You are doing recursion using recur method which can be risky here in the case of continuous inputs as your resources will not be closed right away and can result into further resource starvation issues.
You can simply use infinite while loop.
Improvement1 :
Don't you think that once user inputs bye/see ya/gtg program should close ?
Improvement2 :
Repeated calls to string.toLowerCase() in main method.
Improvement3 :
This line line = lines.skip(count).findFirst().get(); can result into NoSuchElementException
I have added improvement 2 and 3 in the below code.
Here i updated the code below which works as per your details in the question
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.stream.Stream;
public class Main {
public static void main(String args[]) {
System.out.println("Bot: Hello!! My name's HiBot! What's up?");
while (true) {
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
String lowercaseResponse = response.toLowerCase();
if (lowercaseResponse.contains("bye") || lowercaseResponse.contains("see ya")
|| lowercaseResponse.contains("gtg")) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
}
processor(response);
}
}
public static void processor(String reply) {
BufferedReader reader = null;
try {
File file = new File("convos.txt");
if (file.createNewFile())
System.out.println("Conversations file created");
reader = new BufferedReader(new FileReader(file.getName()));
int count = 0;
String line = reader.readLine();
while (line != null) {
count++;
if (line.toLowerCase().contains(reply.toLowerCase())) {
try (Stream<String> lines = Files.lines(Paths.get("convos.txt"))) {
line = lines.skip(count).findFirst().map(Object::toString).orElse("I don't know how to respond");
System.out.println("Bot: " + line);
} catch (IOException e) {
System.out.println("Bot: Something happened while reading conversation file πŸ˜•\n" + e);
}
reader.close();
return;
}
line = reader.readLine();
}
reader.close();
System.out.println("Bot: Sorry, I'm dumb. How should I reply?");
System.out.print("You: ");
Scanner input = new Scanner(System.in).useDelimiter("\\n");
String response = input.next();
teach(reply, response);
} catch (FileNotFoundException e) {
System.out.println("Bot: File not found πŸ˜•\n" + e);
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
} finally {
try {
reader.close();
} catch (IOException e) {
System.out.println("Bot: Something happened while closing the file reader πŸ˜•\n" + e);
}
}
}
public static void teach(String context, String reply) {
try {
try {
FileWriter learn = new FileWriter("convos.txt", true);
PrintWriter out = new PrintWriter(learn);
out.println(context + "\n" + reply);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
System.out.println("Bot: Something happened πŸ˜•\n" + e);
}
System.out.println("Bot: Thank you for teaching me!! I'm smarter now!");
}
}
Output : For the first time
Bot: Hello!! My name's HiBot! What's up?
You: hi
Conversations file created
Bot: Sorry, I'm dumb. How should I reply?
You: hello
Bot: Thank you for teaching me!! I'm smarter now!
You:
hi
Bot: hello
You:
Output : When Convos.txt is created already
Bot: Hello!! My name's HiBot! What's up?
You: hi
Bot: hello
You: hi
Bot: hello
You: hi
Bot: hello
You:
Let me know if i missed anything.

I saw this question because someone edited the question.
Here's one test run. The "convos.txt" file exists and has a couple of response / reply text lines.
Bot: Hello! My name's HiBot! What's up?
You: hi
Bot: Hi
You: how are you
Bot: Fine. How are you?
You: Good
Bot: Sorry, I'm ignorant. How should I reply?
You: That's good to hear.
Bot: Thank you for teaching me a new reply! I'm smarter now!
You: bye
Bot: Ok, see ya. Nice talking to you!
I eliminated the multiple System.in Scanner instances. In the reorganized code, I only needed one Scanner instance. There should only be one System.in Scanner instance in your code.
I created a separate ResponseMap class to hold a HashMap for the response / reply text.
I created a separate FileHandler class to handle the reading and writing of the text file. I read the file into the Map once in the beginning. I write the Map into the file once at the end. Even when you have 10,000 response / reply lines, the entire file should easily fit into memory.
Because I made the Map value a List of String instances, you can manually create multiple replies for the same response. This adds a bit of variety to the chatbot.
Here's the complete runnable code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class ChatbotExample {
public static void main(String[] args) {
new ChatbotExample().runChatbot();
}
public void runChatbot() {
Scanner scanner = new Scanner(System.in);
String[] exitResponses = { "bye", "see ya", "gtg" };
List<String> exitList = Arrays.asList(exitResponses);
boolean running = true;
System.out.println("Bot: Hello! My name's HiBot! What's up?");
ResponseMap responseMap = new ResponseMap();
FileHandler fileHandler = new FileHandler(responseMap);
fileHandler.readFile();
while (running) {
System.out.print("You: ");
String response = scanner.nextLine();
String lowercaseResponse = response.toLowerCase();
if (exitList.contains(lowercaseResponse)) {
System.out.println("Bot: Ok, see ya. Nice talking to you!");
running = false;
} else {
generateReply(scanner, responseMap, lowercaseResponse);
}
}
fileHandler.writeFile();
scanner.close();
}
private void generateReply(Scanner scanner, ResponseMap responseMap,
String lowercaseResponse) {
String text = responseMap.getResponse(lowercaseResponse);
if (text == null) {
System.out.println("Bot: Sorry, I'm ignorant. How should I reply?");
System.out.print("You: ");
String reply = scanner.nextLine();
responseMap.addResponse(lowercaseResponse, reply);
System.out.println("Bot: Thank you for teaching me a new reply! "
+ "I'm smarter now!");
} else {
System.out.println("Bot: " + text);
}
}
public class FileHandler {
private final File file;
private final ResponseMap responseMap;
private final String separator;
public FileHandler(ResponseMap responseMap) {
this.responseMap = responseMap;
this.separator = " ;;; ";
this.file = new File("convos.txt");
createFile(this.file);
}
private void createFile(File file) {
try {
if (file.createNewFile()) {
System.out.println("Conversations file created");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFile() {
try {
BufferedReader reader = new BufferedReader(
new FileReader(file));
String line = reader.readLine();
while (line != null) {
String[] parts = line.split(separator);
responseMap.addResponse(parts[0], parts[1]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile() {
try {
FileWriter writer = new FileWriter(file, false);
PrintWriter output = new PrintWriter(writer);
Map<String, List<String>> responses = responseMap.getResponses();
Set<String> responseSet = responses.keySet();
Iterator<String> iterator = responseSet.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List<String> text = responses.get(key);
for (String reply : text) {
String s = key + separator + reply;
output.println(s);
}
}
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ResponseMap {
private final Map<String, List<String>> responses;
private final Random random;
public ResponseMap() {
this.responses = new HashMap<>();
this.random = new Random();
}
public Map<String, List<String>> getResponses() {
return responses;
}
public String getResponse(String key) {
List<String> possibleResponses = responses.get(key);
if (possibleResponses == null) {
return null;
} else {
int index = random.nextInt(possibleResponses.size());
return possibleResponses.get(index);
}
}
public void addResponse(String key, String text) {
List<String> possibleResponses = responses.get(key);
if (possibleResponses == null) {
possibleResponses = new ArrayList<>();
responses.put(key, possibleResponses);
}
possibleResponses.add(text);
}
}
}

Related

Add data to specific record in CSV file

I have a record in a CSV file and i am trying to add some extra info (a name) to the same specific record with the following code but it does not work. There is no error shown but the info i am trying to add just does not appear. What am i missing ?
public class AddName {
public static void main(String[] args) {
String filepath="Zoo.csv";
String editTerm="Fish";
String addedName="Ron";
addToRecord(filepath,editTerm,addedName);
}
public static void addToRecord(String filepath,String editTerm,String addedName){
String animal= "";
try{
FileWriter fw=new FileWriter(filepath,true);
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
if (animal.equals(editTerm)){
pw.println(editTerm+","+addedName);
pw.flush();
pw.close();
}
System.out.println("Your Record was saved");
}
catch(Exception e){
System.out.println("Your Record was not saved");
e.printStackTrace();
}
}
You could consider using a CSV library to help you out with parsing CSVs because it is more complicated than it looks, especially when it comes down to quoting.
Here's a quick example using OpenCSV that clones the original CSV file and adds "Ron" as necessary:
public class Csv1 {
public static void main(String[] args) throws IOException, CsvValidationException {
addToRecord("animal.csv", "animal-new.csv", "fish", "Ron");
}
public static void addToRecord(String filepathIn, String filepathOut, String editTerm, String addedName)
throws IOException, CsvValidationException {
try (CSVReader reader = new CSVReader(new FileReader(filepathIn))) {
try (CSVWriter writer = new CSVWriter(new FileWriter(filepathOut))) {
String[] values;
while ((values = reader.readNext()) != null) {
if (values.length > 2 && values[0].equals(editTerm)) {
values[1] = addedName;
}
writer.writeNext(values);
}
}
}
}
}
Given the file:
type,name,age
fish,,10
cat,,12
lion,tony,10
will produce:
"type","name","age"
"fish","Ron","10"
"cat","","12"
"lion","tony","10"
(You can look for answers about outputting quotes in the resulting CSV)
Here the requirement is to add an extra column if the animal name matches. It's equivalent to changing a particular line in a file. Here's a simple approach to achieve the same, (Without using any extra libraries),
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class EditLineInFile {
public static void main(String[] args) {
String animal = "Fish";
Path path = Paths.get("C:\\Zoo.csv");
try {
List<String> allLines = Files.readAllLines(path);
int counter = 0;
for (String line : allLines) {
if (line.equals(animal)) {
line += ",Ron";
allLines.set(counter, line);
}
counter++;
}
Files.write(path, allLines);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You may use this code to replace the file content "Fish" to "Fish, Ron"
public static void addToRecord(String filepath, String editTerm, String addedName) {
try (Stream<String> input = Files.lines(Paths.get(filepath));
PrintWriter output = new PrintWriter("Output.csv", "UTF-8"))
{
input.map(s -> s.replaceAll(editTerm, editTerm + "," + addedName))
.forEachOrdered(output::println);
} catch (IOException e) {
e.printStackTrace();
}
}

How to figure out why file is missing when trying to Run Configurations (set an Argument in Java)?

Hello everyone, Java beginner here. I am trying to run some java code in eclipse IDE, and set my args x = 25 from
Run > Run Configurations > Arguments > Apply > Run. However, before I can get to Arguments, I get this error message (see photo below). Does anyone know what this means or why I am getting this? What does this specific '.metadata/.plugins/org.eclipse.debug.core' do?
MY CODE BELOW:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class IOTest {
public IOTest () {
}
public void readFile () {
try {
FileReader file = new FileReader("movies.txt");
BufferedReader br = new BufferedReader(file);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("Unable to load file.");
}
}
public void writeFile () {
try {
FileWriter file = new FileWriter("tvshows.txt");
BufferedWriter bw = new BufferedWriter(file);
bw.write("Seinfeld\n");
bw.write("Breaking Bad\n");
bw.write("The Simpsons\n");
bw.write("Family Guy\n");
bw.close();
} catch (Exception e) {
System.out.println("Unable to load/create file.");
}
}
public static void main(String[] args) {
IOTest test = new IOTest();
test.readFile();
test.writeFile();
if (args.length == 1) {
// Do something.
int x = Integer.parseInt(args[0]);
System.out.println("x = " + x);
} else {
// Do something else.
}
}
}

BufferedWriter without try method IOException

I know this topic has been discussed a lot and I have already read a lot of posts here about that, but I still seem to have trouble.
My problem is that I am also a beginner and I don't really understand how ΔΈwork and the try and catch function.
I have been trying to write to a file some string array, but it doesn't appear in there, nor the catch error is displayed in the console. I don't want to use the try method in this case, because when I am, I cannot use the variable declared for let's say BufferedWriter in other places, I am only restricted to the try method. Otherwise, I get a bug.
This is my code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try(BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))) {
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
System.err.println("Idk when should this appear?");
}
}
}
For the "can't use it anywhere" part of your problem, you could declare the variable outside of the try catch block and only assign it inside. You can do a null check wherever else you want to use it to make sure there's no problems, or assign it another value in the catch block. Like so:
public static void main(String[] args) {
BufferedWriter writer;
String[] anything;
try {
writer = new BufferedWriter(new FileWriter("testing.txt"))) {
anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for (String mem: anything) {
writer.append(mem);
}
writer.close();
} catch (IOException e) {
writer = null;
e.printstacktrace();
}
}
}
if(writer != null){
System.out.println(writer);
}
try and catch it's use for managed the exception. try this code:
import java.io.*;
import java.util.*;
import java.lang.*;
public class FileWrit {
public static void main (String[] args){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("testing.txt"))
String[] anything = new String[3];
writer.write("anything");
anything[0] = "case1";
anything[1] = "This is 1.5";
anything[2] = "Case 3, i do not know how to count";
for(String mem: anything) {
writer.append(mem);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
The System.err.println("Idk when should this appear?"); appear when you have an Exception in your try "an Error".

How do I fix Illegal Start of Expressions with all of my methods?

I have my code. I think it's all right, but it is not. It keeps telling me at the beginning of each method that there is a ';' expected and it's also an 'illegal start of expression' with the void. I do not know how to fix it. Can someone please help me fix these errors?
Here's an example of the Errors:
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:203: error: ';' expected
void arrayList **()** throws FileNotFoundException();
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: illegal start of expression
**void** output()
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: ';' expected
void output **()**
My code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp{
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// scrubber();
//Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
void arrayList() throws FileNotFoundException();
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
//Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
// void scrubber()
// {
//
// }
//
//
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
}
You should use a Java IDE like Eclipse when programming Java, it would point out to you the most obvious mistakes in your code.
You missed a } after the while loop for your readFile() method (thanks to Sweeper for this one).
The syntax in your arrayList() method is wrong.
void arrayList() throws FileNotFoundException(); {
No semicolon at the end of this defintion, no parenthesis at the end too, you are describing the class, not a method. Here is the correct way:
void arrayList() throws FileNotFoundException {
1 useless } at the end of your class file.
Find below your code, with a proper layout and without syntax errors. Please use an IDE next time, that would avoid you an awful lot of trouble.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam ?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
}
void arrayList() throws FileNotFoundException
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
// Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
throws FileNotFoundException();
This should be
throws FileNotFoundException
and similarly in all cases.
Rather trivial. Don't just make up the syntax. Look it up.

The compiler is saying that there is an unreachable statement, what am I doing wrong?

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class airport {
private static final String STDIN_FILENAME = "-";
public static treemap load_database (String database_name) {
treemap tree = new treemap ();
try {
Scanner database = new Scanner (new File (database_name));
for (int linenr = 1; database.hasNextLine(); ++linenr) {
String line = database.nextLine();
if (line.matches ("^\\s*(#.*)?$")) { continue;
//there is a problem with the below line
String[] keyvalue = line.split (":");
if (keyvalue.length != 2) {
misc.warn (database_name, linenr, "invalid line");
continue;
}
tree.put (keyvalue[0], keyvalue[1]);
}
database.close();
}
}
catch (IOException error) {
misc.warn (error.getMessage());
}
return tree;
}
}
if (line.matches ("^\\s*(#.*)?$")) {
continue;
// unreachable code
Execution does not go past continue. So everything after it in that block is unreachable.
Maybe you wanted to close the } after continue?

Categories