Oppgave i MATLAB-Java-oversetting i to deler

Del 1 - rects.m og main.m

Dette MATLAB-programmet holder rede på (koordinatene til) to rektangler, og brukeren kan endre rektanglene og spørre om de overlapper. Skriptet kjøres fra rects.m, som henter funksjonene fra main.m, og er ellers funksjonelt likt som rects.py. Programmet bygger på et eksempel på Guttorm Sindre sin YouTube-kanal.

Oversett programmet til Rects.java, basert på rpncalc1.py oversatt til Java.

 

main.m
%main.m
 
function main()
    global r1x1 r1x2 r2x1 r2x2 r1y1 r1y2 r2y1 r2y2;
    while true
        disp(strcat('Rect1: ', rectangle2String(r1x1, ...
            r1y1, r1x2, r1y2)));
        disp(strcat('Rect2: ', rectangle2String(r2x1, ...
            r2y1, r2x2, r2y2)));
        token = input(' > ', 's');
        if strcmp(token, 'overlaps?')
            disp(rectanglesOverlap());
        elseif strcmp(token, 'exit')
            break
        else
            pos = strfind(token, '=');
            if pos >= 4
                val = str2num(token(pos+1:end));
                if strncmpi(token, 'r1x1', 4)
                    r1x1 = val;
                elseif strncmpi(token, 'r1y1', 4)
                    r1y1 = val;
                elseif strncmpi(token, 'r1x2', 4)
                    r1x2 = val;
                elseif strncmpi(token, 'r1y2', 4)
                    r1y2 = val;
                elseif strncmpi(token, 'r2x1', 4)
                    r2x1 = val;
                elseif strncmpi(token, 'r2y1', 4)
                    r2y1 = val;
                elseif strncmpi(token, 'r2x2', 4)
                    r2x2 = val;
                elseif strncmpi(token, 'r2y2', 4)
                    r2y2 = val;
                end
            end
        end
    end
end
function io =  intervalsOverlap(n1, n2, m1, m2)
    io = ~(n1 > m2 | n2 < m1);
end
function ro =  rectanglesOverlap()
    global r1x1 r1x2 r2x1 r2x2 r1y1 r1y2 r2y1 r2y2;
    if intervalsOverlap(r1x1, r1x2, r2x1, r2x2) ...
        && intervalsOverlap(r1y1, r1y2, r2y1, r2y2)
        ro = 'True';
    else
        ro = 'False';
    end
end
function str = rectangle2String(x1, y1, x2, y2)
    str = strcat('(', num2str(x1), ',', num2str(y1), ...
        ')', ',', '(', num2str(x2), ',', num2str(y2), ')');
end
    

 

 

rects.m
% rects.m
global r1x1;
r1x1 = 0;
global r1y1;
r1y1 = 0;
global r1x2;
r1x2 = 0;
global r1y2;
r1y2 = 0;
global r2x1;
r2x1 = 0;
global r2y1;
r2y1 = 0;
global r2x2;
r2x2 = 0;
global r2y2;
r2y2 = 0;
    
main();
          
    

 



  • No labels