繁体   English   中英

使用代码终止Eclipse(Java)

[英]terminating eclipse with using code (in java)

我一直在使用while(scanner.hasNext()){}方法从文件中读取内容,然后一直执行该程序。 但是我注意到,即使程序(Eclipse)完成了该过程,CPU的使用量仍在急剧增加,并且直到我按下此按钮时,它才会完全停止。 按钮画面

我还使用了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);
        }
    }
}

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

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM