Reputation: 57
I've been always using while(scanner.hasNext()) {} method to read from the file and then execute the program this whole time. But I've notice that CPU usage was drastically increasing even when the program (Eclipse) finishes the process, and it wont stop entirely until I press this button. buttonImage
I also used this function, System.exit(0), to stop the program, but I still have to press the button.
Is there any flaw in my code that makes the program not to stop.
public class HW3
{
/*
Description
*/
public static void main(String[] args) throws FileNotFoundException
{
final File file1 = new File(args[0]);
final File file2 = new File(args[1]);
final Scanner sc1 = new Scanner(file1);
HW3 instance = new HW3 ();
while (sc1.hasNext()) {
print(instance.splitSentence(sc1.nextLine()));
}
sc1.close();
final Scanner sc2 = new Scanner(file2);
while (sc2.hasNext()) {
}
System.exit(1);
}
public void constructTreeNode(String[] stringArray) {
}
private String[] splitSentence (String sentence) {
int wordCount = 1;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ' ') {
wordCount++;
}
}
String[] arr = new String[wordCount];
wordCount = 0;
String temp = "";
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ' ' || i == sentence.length() - 1) {
arr[wordCount] = temp;
wordCount++;
temp = "";
} else {
temp += sentence.charAt(i);
}
}
return arr;
}
private static void print (String[] arr) {
for(String e : arr) {
System.out.println(e);
}
}
}
Upvotes: 0
Views: 54
Reputation: 1703
The issue you are having is with this segment of code.
final Scanner sc2 = new Scanner(file2);
while (sc2.hasNext()) {
}
System.exit(1);
You create a scanner and enter a loop until the scanner has no new data; but you don't read any data from the Scanner. As long as the File file2 wasn't empty, you would enter an infinite loop, and the System.exit(1); code would be unreachable.
This is also the reason why your code never completes, because it is stuck in this loop. The code will complete if it reaches the end of the main() method entry point to your program (That is to say a call to System.exit(int n) is not required unless you specifically want to indicate error).
The fix:
final Scanner sc2 = new Scanner(file2);
while (sc2.hasNext()) {
String line = sc2.nextLine();
}
System.exit(1);
Upvotes: 1