Hello I was given an assignment in which I have to draw 3 circles using their center coordinates and radii which is input by the user. The assignment specifically states that I must input the center and radius, I cannot input the x and y coordinates separately. They must be input as a coordinate pair (x,y).
Here is my code.
import java.util.*;
import java.awt.*;
public class Circles {
static Scanner CONSOLE = new Scanner(System.in);
public static final int PANEL_HEIGHT = 300;
public static final int PANEL_WIDTH = 400;
public static void main (String [] args) {
DrawingPanel panel = new DrawingPanel (PANEL_HEIGHT,PANEL_WIDTH);
Graphics g = panel.getGraphics();
System.out.println();
System.out.println("Red Circle data");
System.out.println("Input center of Red circle: ");
int center1 = CONSOLE.nextInt();
System.out.println("Input radius of Red circle: ");
int radius1 = CONSOLE.nextInt();
System.out.println();
System.out.println("Blue Circle data");
System.out.println("Input center of Blue circle: ");
int center2 = CONSOLE.nextInt();
System.out.println("Input radius of Blue circle: ");
int radius2 = CONSOLE.nextInt();
System.out.println();
System.out.println("Green Circle data");
System.out.println("Input center of Green circle: ");
int center3 = CONSOLE.nextInt();
System.out.println("Input radius of Green circle: ");
int radius3 = CONSOLE.nextInt();
g.setColor(Color.RED);
g.fillOval(center1 -radius1 ,center1-radius1 ,radius1 ,radius1);
g.setColor(Color.BLUE);
g.fillOval(center2 -radius2 ,center2-radius2 ,radius2 ,radius2);
g.setColor(Color.GREEN);
g.fillOval(center3 -radius3 ,center3-radius3 ,radius3 ,radius3);
}
}
My problem is that I don't know how to properly input and store the x and y coordinates as one int. As it is currently it just takes one data point, stores it, and uses it as both x and y.
System.out.println("Red Circle data");
System.out.println("Input center of Red circle: ");
int center1 = CONSOLE.nextInt();
Here is where I know java must ask for the values and store them.
g.setColor(Color.RED);
g.fillOval(center1(THIS SHOULD BE THE X VALUE) -radius1 ,center1(THIS SHOULD BE THE Y VALUE)-radius1 ,radius1 ,radius1);
Then here I have to somehow get the values stored in the above code.
Please help i'm kinda new to this and would appreciate some feedback! Hope what im asking for makes sense! :S
not JAVA coder so I stick to C++, are you sure you want x,y pair in single int ?
1.If yes then just encode it
but you must know the coordinates range
for example if you have 32bit int and your coordinates fits to 16 bit then:
int xy,x,y;
xy = (x&0x0000FFFF) | ((y&0x0000FFFF)<<16); // this makes xy = (x,y)
and if you need to unpack the data again do:
x= xy &0x0000FFFF; if (int(x&00008000)!=0) x|=0xFFFF0000;
y=(xy>>16)&0x0000FFFF; if (int(y&00008000)!=0) y|=0xFFFF0000;
the if at the end restores the missing bits for negative numbers ...
2.if in single variable instead then use
array:
int xy[2],x,y;
xy[0]=x;
xy[1]=y;
or struct/class
int x,y;
struct point { int x,y; } xy;
xy.x=x;
xy.y=y;
Related
this is a Class about calculating diameter,circumference and area of circle that user enter radius value and it gives him diameter,cirucumf... ,
this is the class code:
package circle;
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius=0;
int diameter;
int circumference ;
int area;
int Pi;
Pi=(int) 3.14;
area = (int) (radius*radius*Pi);
circumference =(int)(radius*2*Pi);
diameter = (int)(radius*2);
System.out.print("Enter radius value:");
radius=input.nextInt();
System.out.printf("area is %d%n" , area);
System.out.printf("diameter is %d%n", diameter);
System.out.printf("circumference is %d%n", environment);
}
}
this is what output gives me :
Enter radius value: (for exmaple) 4
area is 0 // (real value is 50.24)
diameter is 0 // (8)
circumference is 0 //(25.12)
what is the code problem?
or how can i fix it?
You read the radius AFTER computing area/environment(?)/diameter. Furthermore, your values are int variables, which also means that your value for pi is just 3. I suggest you correct the order of the statements, and start using double instead of int.
"environment" will be replaced by "circumference". As your excepted output is decimal value. So use float/double instead of int. In your program you are calculating diameter,circumference and area after initialising the value of radius(radius=0) but before getting the value of radius(radius=4). I have modified your code. It seem help you.
package circle;
import java.util.Scanner;
public class Circle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int radius=0;
float diameter;
double circumference ;
double area;
double Pi;
Pi= 3.14;
System.out.print("Enter radius value:");
radius=input.nextInt();
area = (radius*radius*Pi);
circumference =(radius*2*Pi);
diameter = (radius*2);
System.out.printf("area is " + area);
System.out.printf("\ndiameter is "+ diameter);
System.out.printf("\ncircumference is "+ circumference);
}
}
you are calculating the values area/environment(?)/diameter before getting and initializing the radius input.And at that time the default value for radius is set which is 0. Hence it is giving the results of all the parameters as 0.So you will have to re order your code as below:
System.out.print("Enter radius value:");
radius=input.nextInt();
area = (int) (radius*radius*Pi);
environment=(int)(radius*2*Pi);
diameter = (int)(radius*2);
System.out.printf("area is %d%n" , area);
System.out.printf("diameter is %d%n", diameter);
System.out.printf("environment is %d%n", environment);
Trying to make a grid of 2^n size, asking the user for 'n'. I haven't coded in the 2^n part, which is also a little confusing for me. But right now my board will not display correctly when I get input from the user. My drawLine is a diagonal line going through the whole board.
How do I get the board to be displayed correctly?
Here is my code:
import java.awt.*;
import java.util.*;
public class DrawingPanelTest2{
public static void main(String args[]){
// System.out.println("How big do you want your Tromino grid?");
// System.out.println("Please enter a perfect power of 2.");
// int size = stdin.nextInt();
//create a drawing panel of width=400px and height=400px
DrawingPanel panel = new DrawingPanel(400, 400);
//set the background of the panel to CYAN
panel.setBackground(Color.LIGHT_GRAY);
//create a graphic object for the panel
Graphics g = panel.getGraphics();
//draw square
drawFigure_1(g,0,0);
}
public static void drawFigure_1(Graphics g,int x, int y) {
Scanner stdin = new Scanner(System.in);
System.out.println("How big do you want your Tromino grid?");
System.out.println("Please enter a perfect power of 2.");
int size = stdin.nextInt();
//set your drawing color to red
g.setColor(Color.BLACK);
for (int i = 1; i <= size; i++) {
//draw a rectangle, (x,y) is the top-left cordiante of the rectangle, and ((i*z), (i*z))
//are the width and height of the rectangle
g.drawRect(x, y, i * size, i * size);
g.drawLine(x, y, i *size, i *size);
}
g.setColor(Color.BLACK);
}
}
This Graphics g = panel.getGraphics(); is not how custom painting is done.
This Scanner stdin = new Scanner(System.in); is not how you should interacting with the user from within the context of GUI
Start by taking a look at Creating a GUI with Swing and Performing Custom Painting
Take a look at the Graphics Java Docs
Graphics#drawRect takes 4 parameters, the x, y position (top left corner) and the width and height of the rectenagle, whereas Graphics#drawLine takes x1, y1, which is the start point and x2, y2 which is the end point.
So you want to draw a horizontal line, you need to use something more like g.drawLine(x, y, i * size, i); or for a vertical line, something more like g.drawLine(x, y, i, i * size);
If you are trying to draw a grid, then you will need loops, one horizontal and one vertical. You will also need to update the x/y of each rectangle, so that they are placed corrected, so rather than modifying the size parameters, you should be modifying the position parameters
Try something like this:
import java.util.*;
import java.awt.*;
import javax.swing.*;
class myjava{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double pw = input.nextDouble();
myPan panel = new myPan(pw);
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(400, 400);
application.setVisible(true);
}
}
class myPan extends JPanel{
public double pow;
public myPan(double p){
pow = p;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
double num = Math.pow(2,pow);
double across;
double up;
if(pow % 2 == 0){ //is a square
System.out.println("square");
across = Math.pow(num,0.5);
up = across;
}
else{
System.out.println("not");
double x = Math.floor(pow/2);
double y = x + 1;
across = Math.pow(2,x);
up = Math.pow(2,y);
}
System.out.println(across);
System.out.println(up);
//
//
double wid = 400/across; //width of one
double hi = 400/up; //height of one
double nowX = 0;
double nowY = 0;
for(int i = 0; i < up; i++){ //top to bottom
nowX = 0;
for(int j = 0; j < across; j++){
//System.out.print("*");
g.setColor(Color.BLACK);
g.drawRect((int)nowX, (int)nowY, (int)wid, (int)hi);
nowX = nowX + wid;
}
nowY = nowY + hi;
//System.out.print("\n");
}
}
}
I wrote the code for the problem in the title and seem to be having some problems. Can anyone give me some insight or tips on what I am doing wrong. Especially with the "if...else" portion of the code.
Here is the question #9. If you click the link it will show you a printout of the question.
http://s21.postimg.org/nl2tmf5tj/Screen_Shot_2013_09_21_at_6_44_46_PM.png
Here is my code:
import java.util.*;
public class Ch3Ex9 {
/**
* This method asks user for an x,y coordinates of a point, then returns the
* distance to the origin and which quadrant the point is in.
*/
public static void main(String[] args)
{
double xCoord; //x Coordinant initialized to 3
double yCoord; //y Coordinant initalized to 4
double hypo; //hypotenuse
//declare an instance of Scanner to read the datastream from the keyboard
Scanner keyboard = new Scanner(System.in);
//get x Coordinant from the user
System.out.print("Please enter the X coordinant: ");
xCoord = keyboard.nextDouble();
//get Y Coordinate from the user
System.out.print("Please enter the Y coordinant: ");
yCoord = keyboard.nextDouble();
//calculate the hypotenuse which is the length to the origin
hypo = Math.hypot(xCoord, yCoord);
System.out.println("The hypotenuse is "+hypo);
//determine which Quadrant the user-inputted point resides in
if (xCoord>0) && (yCoord>0) //
System.out.println("Point lies in Quadrant I.");
else if (xCoord<0) && (yCoord>0)
System.out.println("Point lies in Quadrant II.");
else if (xCoord<0) && (yCoord<0)
System.out.println("Point lies in Quadrant III.");
else if (xCoord>0) && (yCoord<0)
System.out.println("Point lies in Quadrant IV.")
}
}
There are too many parentheses. Change
if (xCoord>0) && (yCoord>0)
to
if (xCoord>0 && yCoord>0)
and similarly with the others.
I have this code which will find the area of different shapes depending on the inputted shape of the user. The problem is how can I get the inputted measurements(e.g. length, width) from the main class to the Circle, triangle, rectangle and square classes? here's my code.
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
class Circle{
double radius;
void CircleMeasurement(){
radius = r;
}
double getCircleArea(){
return(Math.PI*Math.pow(radius,2));
}
}
class Triangle{
int base, height;
void TriangleMeasurement(){
base = b;
height = h;
}
int getTriangleArea(){
return((base*height)/2);
}
}
class Rectangle{
int length, width;
void RectangleMeasurement(){
length = l;
width = w;
}
int getRectangleArea(){
return(length*width);
}
}
class Square{
int sides;
void SquareMeasurement(){
sides = s;
}
int getSquareArea(){
return( sides * sides);
}
}
class Shapes{
public static void main(String[] args){
String key;
double r;
int b, h, l, w, s;
System.out.println("Welcome!");
System.out.println("Choose your option:");
System.out.println("1 - Circle, 2 - Triangle, 3 - Rectangle, 4 - Square");
Scanner in = new Scanner(System.in);
key = in.nextLine();
if (key=="1" || key =="circle"){
System.out.println("Area for Circle");
System.out.println("Enter radius:");
Scanner.in = new Scanner(System.in);
r = in.nextInt;
Circle circle1 = new Circle();
System.out.println("The area is equal to" + circle1.getCircleArea());
}
else if (key == "2"){
System.out.println("Area for Triangle");
System.out.println("Enter base:");
Scanner.in = new Scanner(System.in);
b = in.nextInt;
System.out.println("Enter height:");
h = in.nextInt;
Triangle triangle1 = new Triangle();
System.out.println("The area is equal to" + triangle1.getTriangleArea());
}
else if (key == "3"){
System.out.println("Area for Rectangle");
System.out.println("Enter length:");
Scanner.in = new Scanner(System.in);
l = in.nextInt;
System.out.println("Enter width:");
w = in.nextInt;
Rectangle rectangle1 = new Rectangle();
System.out.println("The area is equal to" + rectangle1.getRectangleArea());
}
else if (key == "4"){
System.out.println("Area for Square");
System.out.println("Enter side:");
Scanner.in = new Scanner(System.in);
s = in.nextInt;
Square square1 = new Square();
System.out.println("The area is equal to" + square1.getSquareArea());
}
}
}
You can set the appropriate variables at the time of Object creation using constructor.
Circle(int r){
radius = r;
}
Rectangle(int l, int b){
length = l;
breadth = b;
}
Circle c = new Circle(9); //creates a new Circle with radius 9
Rectangle r = new Rectangle(2,3) //Creates a new Rectangle with length as 2, breadth as 3
That said, you can also use setter methods.
Also, using == to compare Strings is frowned upon and often will give you wrong results. Use
.equals() instead.
"Circle".equals(input);
Two things to mention here:
Pass the values taken from scanner to classes as argument to method or constructor. So it can be used by method for furthur calculations. Also using inheritance here will be a good option.
Never use == for string comparision. It will not work, use .equals instead.
One of the problem in your code is that you are comparing string using ==. Strings should be compared using equals method.
change such statements
if (key=="1" || key =="circle"){
to
if (key.equals("1") || key.equals("circle")){
The other problem is that you have not defined constructors with proper arguemnts in your classes such as Circle, Triangle etc. As you are not setting the proper attributes so calling the methods will not provide you the correct results.
For example you need to have constructor in Circle class,to initialize the radius param:
public Circle(int r) {
radius = r;
}
And creating the object of Circle like this, followed by call to getCircleArea should give u the desired result:
Circle circle1 = new Circle(r);
System.out.println("The area is equal to" + circle1.getCircleArea());
You can set values of variables in several ways. First way it's constructor, see rocketboy answer. Second one it's mark your variables as private and use mutator methods. It's recomended way/ See example below:
class Circle{
private double radius;
Circle(double radius){
this.radius = radius;
}
public void setRadius(double radius){
this.radius = radius;
}
public double getRadius(){
return radius;
}
Firs you should create getters and setters.Then
class Circle{
double radius;
public double getRadius(){
return radius;
}
public void setRadius(double r){
radius=r;
}
void CircleMeasurement(){
radius = r;
}
....
r = in.nextInt;
Circle circle1 = new Circle();
circle1.setRadious(r);
I am completely lost on how to sort the coordinates into an array, and find the distance between them. This is the question:
Create a new class called “Circle” that can be used to create customized circle objects. Your class should include the following – be sure to comment your class appropriately:
double radius,
double xPosition,
double yPosition, and
A method that computes the distance from the xPosition and yPosition of one circle to the xPosition and yPosition of another circle. Use the standard distance formula to compute this value. You only need to compute the distance from center point to center point for the purposes of this method. Here’s a method header to get you started:
public double distanceFrom(Circle test)
Create a new class called “Assignment06b”. Do the following in this class:
Prompt the user to enter in a number of circles (i.e. How many circles do you want to create?)
Next, ask the user to enter in the radius, xPosition and yPosition for each circle. Store their input in an array of Circles of the appropriate size.
Finally, Iterate through your array and display distance information for each circle. Ensure that you do not calculate the distance from a given circle back to itself (i.e. no need to compute distance between circle #1 and circle #1) — Here’s a sample running of your program.
Here's what I have so far:
import java.util.Scanner;
public class Assignment06b
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How many circles do you want to create?:");
int amount = input.nextInt();
int[] arrayX = new int [amount];
int[] arrayY = new int [amount];
int counter = 0;
for (counter = 0; counter < amount; counter++)
{
System.out.println("Enter info for Circle #" + (counter + 1));
System.out.print("Radius: ");
double width = input.nextDouble();
System.out.print("X Position: ");
arrayX[counter] = input.nextInt();
System.out.print("Y Position:");
arrayY[counter] = input.nextInt();
}
}
class Circle
{
double radius;
double xPosition;
double yPosition;
Circle(double radius, double xPosition, double yPosition)
{
}
public double distanceFrom(Circle test)
{
double equation = (xPosition-xPosition)*(xPosition-xPosition) + (yPosition-yPosition)*(yPosition-yPosition);
double answer = Math.pow(equation, 0.5);
return answer;
}
}
}
You are tip toeing around object orientation here, change things around so you have an array of circles instead of an array of ints:
Circle[] arrayCircles = new Circle [amount];
Also you aren't setting any values in your circle class, you probably want to fix that:
Circle(double radius, double xPosition, double yPosition)
{
this.radius = radius;
this.xPosition = xPosition;
this.yPosition = yPosition;
}
Then you can add circles to your collection like this:
arrayCirles[0] = new Circle(myRadius, myXPosition, myYPosition);
and call your distanceFrom method call like so:
//Obviously do this in a loop of some kind and make sure they exist first
arrayCircles[0].distanceFrom(arrayCircles[1]);
Hopefully the rest you can figure out yourself
(Also take another look at your distanceFrom method, you want to compare the circle you are passed as a parameter, not to yourself)
I'm currently working in a CAD software and I needed to find the distance between circles (holes) in a square grid/array and I found that the distance between circles (edge to edge) is given by
(L-N*D)/(N-1)
Where:
L is the distance of the array from edge to edge (not to the centre point of the end circle but to the edge of end circles)
N is the number of circles
D is the diameter of the circles
if you measure L from centre point to centre point
(L+D-N*D)/(N-1)
If you're looking to find the distance between centre point to centre point I'm sure you can derive it
Bit late but hopefully this helps someone else!