代码之家  ›  专栏  ›  技术社区  ›  sbot

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

  •  0
  • sbot  · 技术社区  · 8 年前

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

    我也使用了这个函数,系统。退出(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);
            }
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Jim Garrison    8 年前

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

    final Scanner sc2 = new Scanner(file2);
    while (sc2.hasNext()) {
    
    }
    System.exit(1);
    

    创建扫描仪并输入循环,直到扫描仪没有新数据;但您不会从扫描仪读取任何数据。只要文件file2不是空的,您就会进入一个无限循环,系统也会这样。出口(1);代码将无法访问。

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

    修复程序:

    final Scanner sc2 = new Scanner(file2);
    while (sc2.hasNext()) {
        String line = sc2.nextLine();
    }
    System.exit(1);