Java Programming Debug Quiz - java

This quiz is in two parts. First is
public class FixDebugBox {
private int width;
private int length;
private int height;
private double Volume;
public void FixDebugbox() {
length = 1;
width = 1;
height = 1;
}
public FixDebugBox(int width, int length, int height) {
width = width;
length = length;
height = height;
}
public void showData() {
System.out.println("Width: " + width + " Length: " +
length + " Height: " + height);
}
public double getVolume() {
double vol = length * width * height;
return Volume;
}
}
The code above is one half of the quiz, it have the code above complied correctly but the second part I can't
public class FixDebugFour3
// This class uses a FixDebugBox class to instantiate two Box objects
{
public static void main(String args[])
{
int width = 12;
int length = 10;
int height = 8;
FixDebugBox box1 = new FixDebugBox(width, length, height);
FixDebugBox box2 = new FixDebugBox(width, length, height);
System.out.println("The dimensions of the first box are");
box1.showData();
System.out.println("The volume of the first box is");
showVolume(box1);
System.out.println("The dimensions of the first box are");
box2.showData();
System.out.println("The volume of the second box is");
showVolume(box2);
}
public void showVolume() {
double vol = FixDebugBox.getVolume();
System.out.println(vol);
}
}
I keep getting an error with double vol = FixDebugBox.getVolume(); error: non-static method getVolume() cannot be referenced from a static context

FixDebugBox.getVolume();
getVolume is non static method you can not call this with class name, its a public method which you need object to call it.
public void showVolume(FixDebugBox box) {
double vol = box.getVolume();
System.out.println(vol);
}
Now give me the prize. :D

I think you already answered yourself. You need to hold a reference to an instance of FixDebugBox in order to call its non-static methods.

As the error message says, you can't call a non-static method from the static context that is the main method. While you could turn your showVolume() to be a static method and take a FixDebugBox instance as an argument, seeing how FixDebugBox objects already have a getVolume() method, just call it for each instance:
System.out.println(box1.getVolume());
...
System.out.println(box2.getVolume());
Also, don't change the name of your Volume variable to volume. You should use camelCase.

If you move
public void showVolume() {
double vol = FixDebugBox.getVolume();
System.out.println(vol);
}
to the class FixDebugBox
and remove the getVolume() method inclass FixDebugBox , and change the showVolume() method to:
public void showVolume() {
double vol = length * width * height;
Volume = vol;
System.out.println(Volume);
}
That would fix your program. Also boxVolume would be a better name instead of Volume, since variables are not supposed to be written with a capital letter.

Related

Getting .set to work with an object array in Java

So I'm trying to make a program where you put in a radius and it spits out the area, diameter etc. but whenever I run the app it crashes. Here's what I've got if anyone can help that would be much appreciated
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
MeasureC[] mc = new MeasureC[5];
int i=0;
int p =5;
for(i=0;i<=p;i++)
{
System.out.println("What do you want the radius to be?");
double UserRad = scan.nextDouble();
mc[i].setRadius(UserRad);
mc[i].setArea();
mc[i].setDiameter();
mc[i].setCircumfrence();
System.out.println(mc[i].getRadius());
System.out.println(mc[i].getArea());
System.out.println(mc[i].getDiameter());
System.out.println(mc[i].getCircumfrence());
}
Here's the second class:
public class MeasureC {
private double radius, area, diameter, circumfrence;
public double getRadius() {
return radius;
}
public void setRadius(double newRadius) {
radius = newRadius;
}
public double getArea() {
return area;
}
public void setArea() {
area = 3.14*radius;
}
public double getDiameter() {
return diameter;
}
public void setDiameter() {
diameter = 2*radius;
}
public double getCircumfrence() {
return circumfrence;
}
public void setCircumfrence() {
circumfrence = 3.14*(2*radius);
}
MeasureC[] mc = new MeasureC[5];
This doesn't create an array of 5 MeasureC objects, it just allocates the space for them in memory. So, currently, every index points to null. That means that in your for loop when you try and access a particular element in your array you will get an error as .setRadius() etc... is not a method of null:
mc[i].setRadius(UserRad); // mc[i] is null
So, to fix this issue, you can create a new instance of your MeasureC class at each iteration and set it at your index:
for(i = 0; i < p; i++) { // set to i < p as max index in your array is 4 (not 5)
mc[i] = new MeasureC();
// code...
}
Replace:
for(i=0;i<=p;i++)
by:
for(i=0;i<p;i++)
as now you iterate 6 times on 5 dimension array and got ArrayIndexOutOfBoundsException
I assume you get a NullPointerException at the line mc[i].setRadius(UserRad);.
Think about what that means. Then it should be obvious what line you have to add before that to fix the problem.
Hint: Think about how Java does array initializations.
Assuming you want the radius to be the only input data allowed, we can try refactoring your code as (see notes below):
public class MeasureC {
private double radius, area, diameter, circumference;
public MeasureC (double radius) {
diameter = 2.0d * radius;
circumference = Math.pi * diameter;
area = Math.pi * Math.pow(radius, 2);
}
public double getRadius(){
return radius;
}
public double getArea(){
return area;
}
public double getDiameter(){
return diameter;
}
public double getCircumfrence(){
return circumfrence;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int p = 5;
MeasureC[] mc = new MeasureC[p];
for (int i=0; i <= p; i++) {
System.out.println("What do you want the radius to be?");
double userRad = scan.nextDouble();
mc[i] = new Measure(userRad);
System.out.println(mc[i].getRadius());
System.out.println(mc[i].getArea());
System.out.println(mc[i].getDiameter());
System.out.println(mc[i].getCircumfrence());
}
}
Notes:
I expose a single constructor in your MeasureC class which accepts an input radius as a double. Inside that constructor I compute, using that input radius, the diameter, circumference, and area.
Since you only want the circle to be configurable via the radius, I removed setters for the diameter, circumference, and area.
A problem you had in your main() method was that you were not instantiating your MeasureC instances with new. I am doing this now.
Java naming conventions say that variable names should begin with lowercase letters, while class names begin with uppercase. Both are camelcase for subsequent letters. You should stick with this convention.

Multiple Methods in determining Area of Rectangle

The question that I am really stuck on is this:
Write a program that asks the user to enter the width and length of a rectangle, and then display the rectangle’s area. The program should call the following methods:
• getLength – This method should ask the user to enter the rectangle’s length, and then return that value as a double.
• getWidth – This method should ask the user to enter the rectangle’s width, and then return that value as a double.
• getArea – This method should accept the rectangle’s length and width as arguments, and return the rectangle’s area. The area is calculated by multiplying the length by width.
• displayArea – This method should accept the rectangle’s length, width, and area as arguments, and display them in an appropriate message to the screen.
I don't know how to complete this code because right now what I have is this:
import java.util.Scanner;
public class WidthLengthAreaMethods
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
double length;
double width;
double area;
length = getLength();
width = getWidth();
area = getArea(double length, double width);
displayData(length, width, area);
}
public static double getLength()
{
System.out.println("Enter length. ");
length = keyboard.nextDouble();
System.out.println("The length is " + length);
}
public static double getWidth()
{
double width;
System.out.println("Enter width. ");
width = keyboard.nextDouble();
System.out.println("The width is " + width);
}
public static double getArea()
{
double length;
double width;
double area = length * width;
System.out.println("The area is: " + area);
}
public static void displayData(double length, double width, double area)
{
System.out.println(" The length is: \t" + length);
System.out.println(" The width is: \t" + width);
System.out.println(" The area is: \t" + area);
}
}
What am I screwing up on and how would I go about fixing it? I am a beginner in programming so please bear with me :D.
Thanks guys!!
Since your program is broken up into several methods, the data inside each method is local unless you store it inside the class itself.
For example, your helper functions for getLength() and getWidth() wouldn't be able to access your keyboard Scanner unless you declared it outside of the main method, as such:
import java.util.Scanner;
public class WidthLengthAreaMethods {
Scanner keyboard = new Scanner( System.in );
// Initialized within the class, but outside of any methods
public static void main( String[] args ) {
double length = getLength();
double width = getWidth();
double area = getArea( length, width );
displayData( length, width, area );
}
}
Another alternative would be to pass your Scanner to each of the helper methods in their function calls, e.g.
public static double getLength( Scanner keyboard ){}
While passing the Scanner to each function separately would allow your methods to work as intended, the first option is slightly more readable.
The other thing to consider is that when a method has a return value, such as a double in the case of getLength(), getWidth(), and getArea(), the piece of code calling the function is expecting some variable of that type to be returned. In the case of a void function, such as main() or displayData(), the method states that it will not return a variable of any specific type.
Therefore, when you set length to equal getLength(), what you're trying to do is set the value of your local length variable to equal the value coming back from your helper function. If that value will never be sent, the program will most likely be unable to compile - an error will be thrown stating something along the lines of "expected type double" when you try to call that function. To fix the compiler error, a return statement needs to be added in to the helper functions, such as:
Scanner keyboard = new Scanner( System.in );
public static double getWidth() {
System.out.println("Enter width.");
double width = keyboard.nextDouble(); // Sets the value to return to your main function
System.out.println("The width is " + width);
return width; // Returns the value to your main function
// Causes any code underneath the return statement to be ignored
}
Combining all of that should allow the compiler errors to stop, and make your program work correctly.
Here is the working solution
import java.util.Scanner;
public class WidthLengthAreaMethods {
public static void main(String[]args)
{
double length;
double width;
double area;
length = getLength();
width = getWidth();
area = getArea(length, width);
displayData(length, width, area);
}
public static double getLength()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter length. ");
double length = keyboard.nextDouble();
System.out.println("The length is " + length);
return length;
}
public static double getWidth()
{
Scanner keyboard = new Scanner(System.in);
double width;
System.out.println("Enter width. ");
width = keyboard.nextDouble();
System.out.println("The width is " + width);
return width;
}
public static double getArea(double length, double width)
{
double area = length * width;
System.out.println("The area is: " + area);
return area;
}
public static void displayData(double length, double width, double area)
{
System.out.println(" The length is: \t" + length);
System.out.println(" The width is: \t" + width);
System.out.println(" The area is: \t" + area);
}
}

Adding objects with different parameter into the array

So I have this question,
Class circle:
Contains an appropriate attribute to store the radius.
Contains a constructor with one parameter to set the radius.
Contains set and get methods.
Contains a method for calculating the area and another method for calculating the
circumference.
Circle should contain an appropriate attribute to keep track (count) of the number of
Circle objects instantiated.
Class TestCircle:
Create an array of 10 circles of radii 1.0 , 2.0, ..., 10.0.
Print the area and circumference of each circle.
Retrieve and print the number of circles that have been instantiated.
My code is:
public class Circle {
public double radius= 0.0;
public int counter;
public Circle (double radius){
this.radius = radius;
counter++;
}
public Circle (){
}
public void setRadius (double radius){
this.radius = radius;
}
public double getRadius (){
return radius;
}
public double Area (){
return 3.14*radius*radius;
}
public double Circumference (){
return 2*3.14*radius;
}
}
public class TestCircle {
public static void main (String args []){
Circle [] arr = new Circle [10];
System.out.println ("The circumference" + arr.Circumference());
System.out.println ("The area" + arr.Area());
System.out.println ("The number of circles" + arr.counter);
}
}
My question is:
How am I supposed to create 10 circle objects with different radius and add it to the array?
I know that the idea was to add the objects to the array by using the for loop but I couldn't add the radius into the process.
Thank you.
Your code could change like
public class Circle {
private double radius;
private static int numberOfCircles = 0;
public Circle (double radius){
this.radius = radius;
numberOfCircles++;
System.out.println("The circumference : " + getCircumference());
System.out.println("The area : " + getArea());
}
public double getRadius (){
return radius;
}
public double getArea (){
return 3.14*radius*radius;
}
public double getCircumference (){
return 2*3.14*radius;
}
public static int getNumberOfCirclesCreated(){
return numberOfCircles;
}
}
public class TestCircle {
public static void main (String args []) {
Circle [] circles = new Circle [10];
for(int counter=0;counter< circles.length;counter++){
circles[counter]=new Circle((double)(counter+1));
}
System.out.println("Number of circles : " + Circle.getNumberOfCirclesCreated());
}
}
Create for loop that iterates through each array cell. You then create a new Circle object and call its setRadius function. You then set array Cell to equal the Circle object and continue iterating till the array is filled.
Additionally, your counter should be static (as corrected by Fildor). Consider also setting radius as private, seeing as you put in getter/setters.

Inherits in Java

class Box
{
// Instance Variables
double length, ipsos;
double width, mikos;
double height, platos;
// Constructors
public Box ( double side )
{
width = side;
height = side;
length = side;
}
public Box ( double x , double y , double z)
{
platos = y;
ipsos = z;
mikos = x;
}
// Methods
double calculate(double praksi)
{
return 2 * ( width * height +
width * length +
height * length ) ;
}
double volume(double emvadon)
{
return platos * ipsos * mikos;
}
#Override
public String toString() {
return "Volume: " + volume(1) + "\n Calculate: " + calculate(1);
}
}
How can we create a class that inherits MyBox class Box and will be used only for cubes by writing a constructor to ensure the creation of a cube using the second constructor of Box that takes three arguments and in case of an error initializing the cube MyBox to print error message?
I am very new at java, so please explain as simple as possible.
I'm a little confused by why Box has two constructors, and six fields. I would have thought that one constructor and three fields would be enough. But assuming you keep the constructor with three parameters, you can call it from your Cube constructor like this.
The line starting super specifies which Box constructor the Cube constructor should call, and what to pass it. This guarantees that a Cube will always have all three dimensions equal.
public class Cube extends Box {
public Cube(double side) {
super(side, side, side);
}
}

Method - calling methods

import java.util.Scanner;
public class Rectangle
{
public static void main(String[] args)
{
-Don't know how to call method here-
}
/**
* returns the area of a rectangle
* #param height the height of the rectangle
* #param width the width of the rectangle
*/
public static int area (int length, int width)
{
return length * width;
}
/**
* returns the perimeter of a rectangle
* #param height the height of the rectangle
* #param width the width of the rectangle
*/
public static int perimeter (int length, int width)
{
return length + width;
}
/**
* returns the details of the rectangle
* #param height the height of the rectangle
* #param width the width of the rectangle
*/
public static void printRectangleDetails (int length, int width)
{
System.out.println ("This is the length of the rectangle " + length);
System.out.println ("This is the width of the rectangle " + width);
System.out.println (("This is the perimeter of the rectangle " + (length + width)));
System.out.println (("This is the area of the rectangle " + (length * width)));
}
/**
* Read in an integer and return its value
* #param the prompt to be shown to the user
*/
public static int readInteger(String prompt)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer");
int input = scan.nextInt();
return input;
}
}
I'm trying to call the method readInteger to prompt the user to insert the rectangle's height and width. This is my first experience with methods so any help would be appreciated, I'm also not sure if the readInteger method is correct.
Thanks!
In your main() method, you can read the length and width of the rectangle by calling the readInteger() method that you have created in the Rectangle class as:
int length = readInteger(" For Length ");
int width = readInteger("For Width ");
printRectangleDetails(length,width);
First of all, add this line to readInteger() method:
System.out.println (prompt);
You call a method, typical with the following syntax:
methodName();
Example:
To call the area method you say:
public static void main(String[] args)
{
area(2,3);
}
Note: the object is implied in this case since your area method is public and static to the rectangle class which contains the main method.
If area was in a different class you would make the call the method differently, by instantiation first and then a method call on the object.
Try this
public static void main(String[] args) {
Scanner s= new Scanner(System.in) ;
System.out.print("Enter length : " );
int len=Integer.parseInt( s.nextLine()) ;
System.out.print("\nEnter width : ");
int wd=Integer.parseInt( s.nextLine()) ;
printRectangleDetails(len,wd);
}

Categories