使用代码终止eclipse(在java中)

问题描述 投票:0回答:1

我一直在使用while(scanner.hasNext()){}方法从文件中读取,然后一直执行程序。但是我注意到即使程序(Eclipse)完成了这个过程,CPU的使用量也在急剧增加,并且在我按下这个按钮之前它不会完全停止。 buttonImage

我还使用了这个函数System.exit(0)来停止程序,但我仍然需要按下按钮。

我的代码中是否存在任何使程序无法停止的缺陷。

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);
        }
    }
}
java eclipse process
1个回答
1
投票

您遇到的问题是这段代码。

final Scanner sc2 = new Scanner(file2);
while (sc2.hasNext()) {

}
System.exit(1);

您创建一个扫描仪并输入一个循环,直到扫描仪没有新数据;但是您没有从扫描仪中读取任何数据。只要File file2不为空,就会进入无限循环,并且System.exit(1);代码无法访问。

这也是你的代码永远不会完成的原因,因为它停留在这个循环中。如果代码到达程序的main()方法入口点的末尾,则代码将完成(也就是说,除非您特别想要指示错误,否则不需要调用System.exit(int n))。

修复:

final Scanner sc2 = new Scanner(file2);
while (sc2.hasNext()) {
    String line = sc2.nextLine();
}
System.exit(1);
© www.soinside.com 2019 - 2024. All rights reserved.