I’m learning to code in Java. I have this assessment that I need to do: I have to create a java app that will do the following:
-
Allow the user to specify the number of input rectangles (between 3 and 30).
-
Generate the requested number of input rectangles (with random widths and heights) and write them to a file (human readable).
-
Read the randomly generated input rectangles from the file generated in the step above.
-
Display the input rectangles graphically, correctly laid out NEXT to each other
-
Calculate the output rectangles.
-
Display the output rectangles graphically, correctly laid out aside each other. Note: Both the input and output rectangles must be displayed at the same time.
-
Write the output rectangle coordinates into an output file (human readable).”
There rectangles are simple boxes (not fancy coloured etc). I have been struggling with this code, managed to get the Input + error handling done and it displays the rectangles but not as the desired.
Bugs: I need it to accept the amount of rectangles from the user and display them NEXT to each other.
Please find my code below… Thanks in advance.
LB
import java.awt.Graphics;
import javax.swing.JFrame;
import java.util.Random;
import java.util.Scanner;
public class final_rect extends JFrame
{
public final_rect()
{
setTitle("tutorial");
setSize(700,500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
int x = 50;
int y = 50;
Random rnd = new Random();
for (int i=1; i <=5; i++)
{
int width = rnd.nextInt(200);
int height = rnd.nextInt(200);
System.out.println("Rectangle["+ i +"]" + ":(W="+width+ ";H=" +height +")");
g.drawRect( x , y , width, height);
// Update the coordinates for the next rectangle.
x = x + width;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a number between 3 and 30!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number! Please enter a number between 3 and 30!!!");
sc.next();
}
number = sc.nextInt();
}
while (number <3 || number > 30);
System.out.println("Thank you! Got " + number);
test1 t = new test1();
t.paint(null);
}
}
Simple way:
you could make a start position x and y (like 0,0), and keep adding the width to x and/or height to y, and use them on the next retangle to be drawn, instead of fixing the start position (that will make them inside each other).
Oh, just to make sure you know:
drawRect(int startX, int startY, int width, int height)