首页 > 解决方案 > java中奇怪的无限循环

问题描述

//没关系,我大学的一些测试代码似乎在我没有实现任务一部分的所有方法时创建了一个无限循环......

大家好,我知道这可能看起来有点懒惰,但是我大学的 java 编译器声称我的代码中有一个无限循环,我找不到它!这是代码:

public class List {
    private class Node {
        private int value;
        private Node next;

        private Node(int element) {
            this.value = element;
            next = null;
        }

        private boolean hasNext(){
            return next != null;
        }

        private void setNext(Node n){
            next = n;
        }

        private Node getNext(){
            return next;
        }

        private int getElement(){
            return value;
        }

    }

    private static void flip(Node first, Node second) {
        int tmp = first.value;
        first.value = second.value;
        second.value = tmp;
    }

    private Node head;

    public List() {
        head = null;
    }

    public void add(int e){
        if(head == null){
            head = new Node(e);
        }else{
            Node n = head;
            while(n.hasNext()){
                n = n.getNext();
            }
            n.setNext(new Node(e));
        }
    }

    @Override
    public String toString() {
        Node n = head;
        String s = "";
        while(n != null){
            s += n.getElement() + " ";
            n = n.getNext();

        }
        return s;
    }
}

我基本上需要编写一个整数列表,这对我来说似乎很容易,但已经在添加元素的部分我得到了这个错误......

标签: javacompiler-errorsinfinite-loop

解决方案


推荐阅读