[SOLVED] Skip frames

I have trouble with my game loop. The one I have can cause objects to get stuck or teleport through other objects. I know it’s caused when the FPS is low and the game tries to put the objects where they are suppose to be. But it ignore hit detection. My idea is to make the game not render all the frames when it runs slow, to try to get more time for the logic. But I’m not sure how to do that.

@Override
    public void run(){
        while(true){
            double delta = (System.nanoTime() - lastUpdate) / 1000000000.0;
            lastUpdate = System.nanoTime();
            
            world.update(delta); 
            screen.repaint();
            
            if(!maximumFps){
                //100000 convert nanosecound into milisecound. It's what 1 milisecound is in nanosecounds
                try{ Thread.sleep((lastUpdate-System.nanoTime() + optimalTime) / 1000000); }catch(Exception e){}
            }else{
                try{ Thread.sleep(1); }catch(Exception e){}
            }
        }
    }