Java: Creating/Using an Array of Records - java

I have an assignment that asks us to create a program to compute the dimensions (width and height) of a screen given the diagonal and aspect ratio.
I'm supposed to ask the user for the inputs (diagonal and aspect ratio), call a subprogram to compute the dimensions (height and width), then display the results. The subprogram needs to return both width and height, so I need to create a 'record' that combines the two into one unit. PLEASE HELP!
The formulas are:
x = sqrt(y^2 / (1+ a^2))
h=x
w=ax
where:
h=height
w=width
y=diagonal
a=aspect ratio
Here's what I have so far:
package hw3;
//A. Nelson, a program to compute the dimensions (width & height)
//of a screen given the diagonal & aspect ratio
import java.util.Scanner;
class Screen
{
public int height, width;
}
public class Hw3 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Screen dimensions = new Screen();
//Variables
int yDiagonal, aAspect;
//Program description
System.out.println("This program will compute the dimensions (width and height)" +
"\nof a screen given the diagonal and aspect ratio.");
//Prompt 1: Diagonal
System.out.print("\nPlease enter the following dimensions:" +
"\n\tDiagonal (inches): ");
yDiagonal = keyboard.nextInt();
//Prompt 2: Aspect
System.out.print("\tAspect Ratio: ");
aAspect = keyboard.nextInt();
//Compute Dimensions
System.out.println("\nHere are the dimensions of the screen:" +
"\nHave a nice day!");
}
public Screen computeDimensions(int yDiagonal,int aAspect)
{
int answer;
answer = (int) Math.sqrt( Math.pow(yDiagonal,2) / (1+Math.pow(aAspect,2)));
Screen [] dimensions = new Screen[2];
Screen.height = answer;
Screen.width = aAspect*answer;
return Screen;
}
}

You have several problems in your code
First, just declaring the method doesn't actually invoke the method (i.e. the method is never executed). So at the end of your main method you need
dimensions = computeDimensions(yDiagonal, aAspect);
However, there are other serious issues.
First, you've declared aAspect as an integer, while screen aspect ratios normally have values that are NOT integer ratios, such as 1920x1080 or 16:9, which is 1.7777... Same for other aspect ratios, so you'll need to accept a floating-point value instead of an integer, or write code to parse strings such as "16:9" and calculate the ratio.
Then inside computeDimensions you create an array of Screen objects, where you only need one. The correct code here is
Screen result = new Screen();
result.height = answer;
result.width = aAspect*answer;
return result;
and then in the main method after the call to computeDimensions you must print the values returned in dimensions.
There could be other problems as well in your definition of the algorithm. I'm not going to write your entire assignment for you, but this should get you pointed in the right direction.

Just in addition to Jim's right answer:
Here is an example on how to call the computeDimensions method from your main method:
public static void main(String[] args) {
...
//Compute Dimensions
Screen s = computeDimensions(yDiagonal, aAspect);
System.out.println("\nHere are the dimensions of the screen: height=" +
s.height + ", width=" + s.width + "\nHave a nice day!");
}
Also, you have to add the keyword static to your computeDimensions method or the program won't compile, because you are calling from a static context:
public static Screen computeDimensions(int yDiagonal,int aAspect) {
...
}

Related

How to use Java Methods/ Parameters

I have coded a program using separate parts to find & display the area and perimeter of a rectangle. I am now supposed to create a void to display the length, width, area and perimeter. However, I can't seem to get it to display when I run the program. I will pop in my code and then the instructions of the task underneath in case I haven't explained it well enough.
public class Rectangle
{
public static void main(String[] args)
{
System.out.println (area(10,15));
System.out.println (perimeter(10, 15));
}
/**
* Returns the area of a rectangle
*/
public static int area (int length, int width)
{
return length * width;
}
/**
* Returns the perimeter of the rectangle
*/
public static int perimeter (int length, int width)
{
return 2 * (length + width);
}
public static void printRectangleDetails(int length, int width, int area, int perimeter)
{
System.out.println ("The length of the rectangle is " + length);
System.out.println ("The width of the rectangle is " + width);
System.out.println ("The area of the rectangle is " + area);
System.out.println ("The perimeter of the rectangle is " + perimeter);
}
}
The task information:
"Write a method called printRectangleDetailswhich, when given the height and width of a rectangle, prints four lines of output stating the height, width, area, and perimeter of the rectangle. The output should include suitable text explaining what the numbers area. Add suitable comments to the new method.printRectangleDetails()is a different kind of method fromareaand perimeter. It performs some actions (printing output) but does not return any result when it is called. Its output type must therefore be voidto show that it does not return a value, and it is an example of a void method. A call to a void method can be used as a standalone statement in your program. However, because a void method does not return a value, it cannot be used where an expression with a value is expected. Methods which return a value (non-void methods) can be used as both standalone statements and as expressions."
Edit - I have now seen this on the instructions "Replace the code in the main method with suitable calls of your printRectangleDetails()method." does this mean I should change the void main(String[] args) section to printRectangleDetails() & if so, how would I do this?
Other methods can be called inside methods, you are passing an int area and an int perimeter in your printRectangleDetails parentheses however, you do not have to do this. Your printRectangleDetails method should only know the width and height, and inside the method functions then it will call the other methods area(width, height) and perimeter(width, height) and pass the width and height to them.
For the Edit question, you do not have to change the main(String[] args), but since your new method printRectangleDetails already prints all the info of the rectangle including area and perimeter, then all you have to do is replace any methods inside main with a single call to printRectangleDetails.

Does Java Swing limit how many items it will draw?

I'm writing a recursive method in Java that creates essentially creates a circle tree. It draws a circle at the top and center and then the method gets called again and creates the circles one level lower on the y axis and half way to the left and right of the new circle. I was successful but only for a certain number of objects to be drawn This is what it looks like
public void test(Graphics g, int y, int num, double instance) {
if(num<50) {
int r = 20;
for(int i=1;i<=instance;i++) {
if(i%2==1) {
g.fillOval(getWidth() * i / num, y, r, r);
}
}
if(instance==1){
instance= 2* instance;
}
test(g, y + 20, num * 2, Math.pow(instance,2.0));
}
Everything works perfectly until I try to increase the number in "if(num<50)" to exactly "if(num<65)". When I change that the JFrame appears but now it is empty and it seems like the program is frozen. I want to increase that so that I can fill the Jframe with the circle tree. Why is it doing that? Looking forward to your response! Thank you!
I found the issue. I don't know why I choose to use Math power when I only had to use *2 and that fixed the whole program.

Recursive methods Java

Recursion always has been something I have a hard time with. I have a test tomorrow and he said there will be some Recursion on the test so I want to be prepared.
The problem I am trying to do says this:
Given a class Rectangle with instance variables width and height, provide a recursive getArea() method. Construct a rectangle whose width is one less than the original and call its getArea method.
So I know that in recursion you end up calling the method inside itself with a simplified rendition. Like, I know somewhere in getArea(int n) I will have to call getArea(n - 1). I am just not sure what to do with width and height.
So I have this:
public int getArea()
{
if (width == 1) {
// Base case here. Not sure what to do for this.
return 1; // Maybe? I'm not sure.
} else {
Rectangle smallerRect = new Rectangle (width - 1);
int smallerArea = smallerRect.getArea();
return smallerArea + height + width;
}
}
Can anyone help me better understand recursion or maybe how to go about thinking through a recursive function? Thanks.
You've got the recursion itself right, with a base case and a recursive case, and a correct reduction of the parameter in the recursive call (except that, as the commenters have noted, you also need to specify the height of the new rectangle). It's only the geometry that needs fixing: height doesn't change during the recursion; what is the area of the base case rectangle, which has got width 1 and height height? And if you are told the area of the rectangle with width width - 1 and height height, how much extra area do you get by adding a strip of width 1 and height height?
For later use: while mathematically correct, this is a terrible way to compute the area of a rectangle, so please don't do this outside of exam/homework situations :-)
Something like this perhaps? It's basically just multiplying width by height with recursion...
public int getArea() {
return getArea(width);
}
private int getArea(int x) {
return x == 0 ? 0 : height + getArea(x-1);
}
public int getArea()
{
if (width == 1) {
// Base case
return height; // Area = width(1)*height
} else {
Rectangle smallerRect = new Rectangle (width - 1, height);
int smallerArea = smallerRect.getArea();
return smallerArea + height;
}
}

How can I make a method repeat itself? Java

I have a method that fills an array and I need to find a way to make it repeat a number of times. The purpose is to iterate and reiterate the density of a planet to narrow its mass,gravity and densities at specific points which are concentric shells. This is my first program but, I have learned a decent amount while working on this I think. Thanks everyone
Here is my code sample of the density calculation. I probably included too much but oh well. So I need to make this iterate selected number of times. Each iteration needs to be put back into the mass calculation which will then be put back into the gravity calculation. And then the show starts again.
public class ItrDensityGrid {
public double itrrho[];
double b = InitialConditions.bmod;
// Iterating grid of densities
public ItrDensityGrid(int shells, double radius, double mass){
GravityGrid gg = new GravityGrid(shells, radius, mass);
for(int k = shells; k >= 0; k--){
itrrho[k] = (itrrho[k]*(1+(gg.alpha[k]*(1.0 / 2)))*(1 / (1-((gg.alpha[k])*(1.0 / 2)))));
}
}
}
This can be achieved with the help of Recursion, or looping.
In recursion, you call the method again from inside of the method itself. Make sure to call (or return) conditionally, otherwise, it may lead to infinite loop!
Here is an example with recursion:
public planetMars (double density, double mass) {
// do your calculations
density = density / 10.05312;
mass = mass / 7.2378;
myArray[] = density; // or whatever you want
// if calculations have not narrowed enough, call recursively
if ( density > 5.2)
planetMars (density, mass);
}
alternatively, with loop, you may do something like:
public planetMars (double density, double mass) {
// loop unless the calculation is not cool
while ( density > 5.2) {
// do your calculations
density = density / 10.05312;
mass = mass / 7.2378;
myArray[] = density; // or whatever you want
}
}
you could make a function which checks if the tolerances of your calculations are already good enough, here is some "pseudocode"
while(toleranceIsGood(planet) == false)
{
planet = calculatePlanet(planet);
}
planet would be the array. of course you can implement things like Endless loop detection etc

Writing class method for test class

public class CirclTest{
public static void main(String[] args){
Circle first=new Circle('R',3.0);
Circle first=new Circle('R',3.0);
Circle second=new Circle();
System.out.println("first's radius is " + first.getRadius());
System.out.println("first's area is " + first.getArea());
System.out.println("second's area is " + second.getArea());
if(first.hasLargerAreaThan(20)){
System.out.println("first's area is larger than 20. ");
}else{
System.out.println("first's area is smaller than 20. ");
}
}
}
So i am supposed to write a circle class.This is what i have done.
public class Circle{
private double radius=0.0;
private double area=0.0;
private char colour=' ';
public Circle(char colour,double radius){
this.colour=colour;
this.radius=radius;
}
public Circle(){
radius=0;
colour='B';
}
public char getColour(){
return colour;
}
public double getRadius(){
return radius;
}
public double getArea(){
return area;
}
}
I am actually confused on how to write a class.Like i know i need to initialize the variables by private etc.And i need to build a constructor but somehow this code above does not work.the test method is correct.But i have to use it to implement my class.
You're declaring the variable
Circle first
twice. If you want to reassign its value, just do
first=new Circle('R',3.0);
And inside the if statement you're calling
first.hasLargerAreaThan(20)
when I don't see such a method defined in your class.
Can you please what you mean by the code does not work? If you are referring to area not getting calculated correct and is always 0, that is happening because you have a default value for the same as 0 and are never calculating it. You might want to put calculation logic in getArea() method.
First, you're going to want to use a testing framework to assert the validity of your code, if that's what is required. Look into JUnit.
A sample assertion of if the area was larger than some value would be written like this.
#Test
public void assertArea_calculatedProperly() {
//given that the radius is 5,
Circle c = new Circle('R', 5);
//when I get the area...
double result = c.getArea();
//then I expect it to be around 78.53981634.
assertTrue(result < 78.6);
assertTrue(result > 78.5);
}
Second, your getArea isn't actually getting the area. There's nothing in your code to retrieve, then calculate the area. You're not even using Math.PI. I would recommend that you implement that - but use the unit test as a valid way to assert that you're going to get an appropriate response back.

Categories

Resources