I am a beginner in programming and am having trouble with using constructors, specifically. I have to write a program for one of my labs that must consist only of:
Three instance variables – length, width and height (each of type double)
One instance variables – input (type Scanner) initialized to System.in
Default constructor (no-arg) – initialize all three instance variables to 1
Initial constructor – initialize all three instance variables
Copy constructor – copy Box
inputWidth, inputLength, and inputHeight methods that set the instance variables based on user input have not parameters and do not
return a value.
a displayDimensions method that displays the length X Width X height (separated by “X”) and does not return a value.
a calcVolume method that has no parameters and calculates the volume of the box
We also were given application BoxTest in which the output must
exactly match the following:
Default dimensions are 1.0 X 1.0 X 1.0 with volume of 1.0
Initial dimensions are 8.5 X 11.0 X 1.0 with volume of 93.5
Copied dimensions are 8.5 X 11.0 X 1.0 with volume of 93.5
Update dimensions
Enter length: 1
Enter width: 2
Enter height: 3
Updated dimensions are 1.0 X 2.0 X 3.0 with volume of 6.0
Here's my code:
import java.util.Scanner;
public class Box {
public static void main(String args[]) {
double length, width, height;
Scanner input=new Scanner(System.in);
new Box() { //
Box defaultBox=new Box();
double length = 1.0;
double width = 1.0;
double height = 1.0;
System.out.print("Default dimensions are " + length + " X " + width + " X " + height);
defaultBox.displayDimensions();
System.out.println(" with volume of "+defaultBox.calcVolume());
Box initialBox=new Box(length, width, height);
length = 8.5;
width = 11.0;
height = 1.0;
System.out.print("Initial dimensions are " + length + " X " + width + " X " + height);
initialBox.displayDimensions();
System.out.println(" with volume of "+initialBox.calcVolume());
Box copyBox=new Box(initialBox);
System.out.print("Copied dimensions are " + length + " X " + width + " X " + height);
copyBox.displayDimensions();
System.out.println(" with volume of "+copyBox.calcVolume());
System.out.println("\nUpdate dimensions");
initialBox.inputLength();
initialBox.inputWidth();
initialBox.inputHeight();
System.out.print("Updated dimensions are ");
initialBox.displayDimensions();
System.out.println(" with volume of "+initialBox.calcVolume());
}
double inputLength() {
Scanner input;
double length = input.nextDouble();
}
double inputWidth() {
Scanner input;
double width = input.nextDouble();
}
double inputHeight() {
Scanner input;
double height = input.nextDouble();
}
double displayDimensions(double length, double width, double height) {
Scanner input;
}
double calcVolume() {
}
}
What am I missing? My program will not compile and gives the error message
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error, insert "Identifier (" to complete MethodHeaderName
Syntax error, insert ")" to complete MethodDeclaration
Syntax error, insert ";" to complete MethodDeclaration
Syntax error, insert "}" to complete ClassBody
at Box.main(Box.java:18)
As I said in the comments, you have put everything in main. Don't do that. As it is, your Box class is basically empty, and you are currently almost creating an anonymous sub-class in main. Your directions do not mention a main, but are pretty straight forward. You were supposed to write something like
public class Box {
// Three instance variables – length, width and height (each of type double)
private double length, width, height;
// One instance variables – input (type Scanner) initialized to System.in
private Scanner input = new Scanner(System.in);
// Default constructor (no-arg) – initialize all three instance variables to 1
public Box() {
this.length = this.width = this.height = 1;
}
// Initial constructor – initialize all three instance variables
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
// Copy constructor – copy Box
public Box(Box b) {
this(b.length, b.width, b.height);
}
// inputWidth, inputLength, and inputHeight methods that set the instance
// variables based on user input have not parameters and do not return a value.
public void inputWidth() {
this.width = input.nextDouble();
}
public void inputLength() {
this.length = input.nextDouble();
}
public void inputHeight() {
this.height = input.nextDouble();
}
// a displayDimensions method that displays the length X Width X height
// (separated by “X”) and does not return a value.
public void displayDimensions() {
System.out.printf("%.2fX%.2fX%.2f%n", length, width, height);
}
// a calcVolume method that has no parameters and calculates the volume of the
// box
public double calcVolume() {
return length * width * height;
}
}
Create a Java class named Package that contains the following:
Package should have three private instance variables of type double named length, width, and height.
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);
I have been assigned the following task for an introductory java course:
You should write a class that represents a circle object and includes the following:
Private class variables that store the radius and centre coordinates of the object.
Constructors to create circle objects with nothing supplied, with just a radius value supplied and with a radius and centre coordinates supplied.
Public instance methods that allow the radius and centre coordinates to be set and retrieved (often known as set/get methods).
Public instance methods that return the circumference and area of the circle.
A public class method that tests if two circle objects overlap or not
Here is my code:
import java.lang.Math;
public class Circle {
private double xCentre, yCentre, Radius;
// constructors
public Circle() {
xCentre = 0.0;
yCentre = 0.0;
Radius = 1.0;
}
public Circle(double R) {
xCentre = 0.0;
yCentre = 0.0;
Radius = R;
}
public Circle(double x, double y, double R) {
xCentre = x;
yCentre = y;
Radius = R;
}
//getters
public double getX() {
return xCentre;
}
public double getY() {
return yCentre;
}
public double getRadius() {
return Radius;
}
//setters
public void setX(double NewX) {
xCentre = NewX;
}
public void setY(double NewY) {
yCentre = NewY;
}
public void setRadius(double NewR) {
Radius = NewR;
}
//calculate circumference and area
public double Circumference() {
return 2*Math.PI*Radius;
}
public double Area() {
return Math.PI*Radius*Radius;
}
//determine overlap
public static double Overlap(Circle c1, Circle c2) {
double xDelta = c1.getX() - c2.getX();
double yDelta = c1.getY() - c2.getY();
double separation = Math.sqrt(xDelta*xDelta + yDelta*yDelta);
double radii = c1.getRadius() + c2.getRadius();
return separation - radii;
}
}
}
and
import java.io.Console;
public class cp6 {
public static void main(String args[]){
//Set up the Console
Console myConsole = System.console();
//Declare cirlce
Circle first = new Circle(2.0,4.0,6.0);
myConsole.printf("Circumference of first circle is ", first.Circumference(), "\n");
myConsole.printf("Area of first circle is ", first.Circumference(), "/n");
first.setRadius(2);
first.setX(2);
first.setY(2);
myConsole.printf("New X of first circle is ", first.getX(), "/n");
myConsole.printf("New Y of first circle is ", first.getY(), "/n");
myConsole.printf("New Radius of first circle is ", first.getRadius(), "/n");
Circle second = new Circle(-1.0,3.0,5.0);
Circle third = new Circle(1,1,1);
if (Circle.Overlap(second, third) <= 0) {
myConsole.printf("Second and third circles overlap");
}
else {
myConsole.printf("Second and third circles do not overlap");
}
myConsole.printf("New Y of first circle is ", first.getY());
Calculate and print out distance between them using the class method
myConsole.printf("Distance between first and second is : %.5g\n", Circle.Overlap(first, second));
}
}
The second program just has to demonstrate each aspect addressed in the brief I pasted at the top and I've only a rough idea of how to do this so if what I'm doing seems stupid to any of you please offer suggestions of what else I can do.
Your problem is that you're using the Console.printf() method incorrectly.
The first parameter to this method should be a format, and it has to have placeholders inside it for the other parameters. Read up on it in The Java Platform documentation. In fact, you should familiarize yourself with the Java platform documentation. You need to use it often to make sure you're calling methods correctly or what methods are available in a given class.
So, your printout lines should actually have been:
myConsole.printf("Circumference of first circle is %.2f%n", first.Circumference());
myConsole.printf("Area of first circle is %.2f%n", first.Area());
...etc.
The format %.2f means "The corresponding parameter is a floating-point number. Display it with a precision of 2 digits after the decimal point". The %n replaces your "\n" - the whole "template" of the print should be just in the format string. And in this type of format, one should use %n instead of \n.
I'm not sure why you opted for using the system console rather than the usual System.out.println(). If you choose to go with System.out, there is also a printf() method there that works exactly as Console.printf() - the first parameter is a format, the others are embedded in it.
One last comment: there are conventions when writing Java code:
Indent your code properly
Class names' first letter is always uppercase.
Non-constant fields and local variable names' first letter is always lowercase.
Method names also start with a lowercase letter.
I am new to java and trying to understand the use of this keyword in java.As per documentation if instance and local variables have same name then local variables mask the instance variables.We use this keyword so that instance variable may not be masked by local variable.Below is the program i was writing to understand the use of this key work but even after use of this keyword instance variable is still getting masked.
class Box{
int height=5;
int length=10;
int breadth=15;
int CalcVol(){
int vol = height*breadth*length;
return vol;
}
Box(int height, int length,int breadth){
this.height = height;
length = length;
breadth = breadth;
System.out.println("height is " + height);
}
}
class MyBox{
public static void main(String args[]){
Box mybox1 = new Box(10, 20, 30);
int vol=mybox1.CalcVol();
System.out.println("volume is" + vol);
}
}
What i am thinking is that variable "height" printed in Box constructor should print 5 ie value of instance variable but its printing 10 ie the value passed as parameter.Please help me on this.
You need to add this before every field you want to access :
Box(int height, int length,int breadth){
// ...and move this statement to the beginning, otherwise this.height gets overriden.
System.out.println("height is " + this.height);
this.height = height;
this.length = length;
this.breadth = breadth;
}
Otherwise, length = length and breadth = breadth have no effect.
It is a name collision problem.
Within the constructor Box are the parameters height, length, and breadth. Those are also names of three fields within Box.
In Java, one considers member variables and block variables to be "closer" than field variables. As such, if you use the exact same name for both (as you have done), the assignment
height = height
will assign the parameter height to the exact same value it held (effectively a noop).
To avoid this issue, you will specify which height you are assigning.
this.height = height;
which is shorthand for "this class's height" or "the field height". When there is no name collision, the compiler will assume you meant the field variable; because there is nothing else with that name in the block.
As an aside, this is a really good reason to learn how to use the final keyword. Final means that the variable can be assigned once, and only once. It prevents it from being reassigned in situations you probably would never want.
For example
public Box(final int height, final int width, final int breadth) {
would then throw a compliation error upon
height = height;
because you are reassigning the value of height. Such techniques are very valuable when writing code, because they prevent you from writing something you think is a field assignment, when you really wrote a parameter assignment.
For your class:
class Box{
int height=5;
int length=10;
int breadth=15;
Box(int height, int length,int breadth){
this.height = height;
length = length;
breadth = breadth;
System.out.println("height is " + height);
}
}
When you construct Box, the following is happening:
Instance variable height is being set to the constructor parameter height
Constructor parameter length is being set to itself (not changing instance variable length)
Constructor parameter breadth is being set to itself (not changing instance variable breadth).
What you probably want to do in the constructor is set your instance variables with the values passed into the constructor like this:
Box(int height, int length,int breadth){
this.height = height;
this.length = length;
this.breadth = breadth;
}
You are performing an assignment here, which will make this.height take on the value of the parameter height.
this.height = height;
If you want to print the original value of this.height, put the print above the assignment and print with this.height.
System.out.println("height was " + this.height);
More completely, your constructor should look like this. Note that you need to prefix with the this keyword on every access to any instance variable that is shadowed by a local variable.
Box(int height, int length,int breadth){
System.out.println("height was " + this.height);
this.height = height;
this.length = length;
this.breadth = breadth;
}
Rather than not understanding the usage of the this keyboard in Java, I think OP isn't understanding object oriented programming in general, seeing how he's trying to print out "5" when the value has already changed. The this keyword becomes a lot less confusing once you understand that concept.
Suppose you have your class Box, and it only has one value, height:
class Box {
// This is a instance variable, that is, each new instance of Box
// has a different height variable even if they are all equal to 5
// initially. It's a different variable in memory.
int height = 5;
// Here's our constructor that sets this instance's value of height
Box(int height){
this.height = height;
}
When you make a new Box, you are making a new Box Object - for each object the height will initially start at 5, but you are changing the height of that instance of Box in your constructor.
Box box1 = new Box(10); // Height was originally 5, but changed to 10 in the constructor
Box box2 = new Box(20); // Height was originally 5, but changed to 20 in the constructor
Box box3 = new Box(30); // Height was originally 5, but changed to 30 in the constructor
When you get to the following line of code in your original program:
System.out.println("height is " + height);
It doesn't matter if it was this.height or height, it will never return 5. You already changed the value of the instance's height in the constructor.
So then. How do we print out a default height of 5? You can't. Not with the same variable name. You have to define constants in the class (like final int HEIGHT = 5) which represent the default values for that class, or use another constructor that doesn't set those values.
class Box{
int height=5;
int length=10;
int breadth=15;
int CalcVol(){
int vol = height*breadth*length;
return vol;
}
Box() {
System.out.println("height is " + height);
}
Box(int height, int length,int breadth) {
this.height = height;
this.length = length;
this.breadth = breadth;
System.out.println("height is " + height);
}
}
class MyBox{
public static void main(String args[]){
Box mybox1 = new Box(10, 20, 30); // this will never print 5, and always 10
Box mybox2 = new Box(); // this will always print 5
}
}
However, if you move the print statement above the assignment and used this.height, like Maxim Bernard did, then it will print out 5, since we didn't change the value yet.
Box(int height, int length,int breadth) {
System.out.println("height is " + this.height); // this will print out 5
this.height = height;
this.length = length;
this.breadth = breadth;
}
If this is really confusing, rather than trying to understand Java's this keyword I suggest just reading a few articles on OOP. You'll understand then that this simply means the current instance of a class.
Can someone please tell me what's wrong with this simple program? I'm getting output as "0".
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Doconstructor d1 = new Doconstructor(10, 15);
// you are assigning values for x and y
But
Doconstructor (int x,int y)
{
int area; // you are never use x and y values for calculation
area = length *width; // so area remain 0 since current length and width is 0
System.out.println("area ="+area);
}
You need to change your code as follows.
Doconstructor (int x,int y)
{
int area;
this.length=x;
this.width=y;
area = length *width;
System.out.println("area ="+area);
}
Edit like this:-
package myConst;
public class Doconstructor
{
int length,width;
Doconstructor(int x, int y)
{
int area;
this.length=x;//Using this for current object
this.width=y;//Using this for current object
area = length * width;
System.out.println("area ="+area);
}
}
class work
{
public static void main(String args[])
{
Doconstructor d1 = new Doconstructor(10, 15);
}
}
Your output will be:
area =150
Must read this :
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
You are not setting the values of length and width and by default they are both 0. You might have to do this:
Doconstructor(int x, int y){
int area;
area = x * y;
length = x;
width = y;
System.out.println("Area = "+area);
}
You're not using the variable values you pass to the constructor in it but rather the length and width values that have been initialized to 0. You want area = x * y; instead.
The length and width fields are implicitly initialized to 0. Multiply them and you get 0.
I think what you want is
length = y ;
width = x ;
int area = length * width ;
System.out.println("area ="+area);
You have this:
public class Doconstructor {
int length,width;
Doconstructor (int x,int y)
{
int area;
area = length *width;
System.out.println("area ="+area);
}
}
At no point do you set length or width equal to anything. Their initial values are 0 and your program is doing precisely what you told it to do. area = length * width = 0 * 0 = 0.
You also are not doing anything with the x or y that you passed to the constructor, but this probably was not your intention. When writing programs, you basically need to clearly instruct the computer to do what you want to do. It's not going to guess what you want. If you ignore x and y, and don't assign any values to length or width, then that is precisely what will happen and you cannot be surprised when you see the results you see.
you are writing int length,width at class level so length and width are set to 0 as default.
After that in the constructor you are not setting any values to length and width so you are the values for length and width are 0.Hence area is also 0
Please check this link for list of default values
Constructors are used to create objects and to set the attributes. You are not setting the attributes in your constructor. Here is how your constructor should look like.
Doconstructor(int x, int y){
length = x;
width = y;
}
Secondly you are mixing the logic of a constructor and a method. You are doing the calculation of area, which seems to be a perfect fit for another method in your class. so better move that logic in a separate method:
public int calculateArea() {
int area;
area = x * y;
return area;
}
Finally create an object using constructor to set the attributes length and width. And then call calculateArea method to do the business logic of calculating area.
public static void main(String args[]){
Doconstructor d1 = new Doconstructor(10, 15); // create object and set length & width
d1.calculateArea();
}
you are not assigning the value of x and y to the variables width and length. The default value of width and length are (int) 0. Thats why you are getting the output (0*0=0). First assign the values to the variables or use "area=x*y;" .
So im trying to create a program that reads a word and then sets of 2 numbers that specify rectangles, (w, h). When the word is “area”, the program should calculate and print the area. When the word is “perimeter”, calculate and print the perimeter. When the word is “quit”, exit the program, without reading the numbers.
The output should look like this:
java Rectangle1
? area 1 2 3 4
Area of (1.0, 2.0, 3.0, 4.0) = 12.0
? perimeter 1 2 3 4
Perimeter of (1.0, 2.0, 3.0, 4.0) = 14.0
? area 2 3 4 5
Area of (2.0, 3.0, 4.0, 5.0) = 20.0
? quit
$
I am able to get the program to store the width and height first and then read area or perimeter so it looks like this:
$ java Rectangle1
To find the area or perimeter of a rectangle
Enter the Length from 1 to 20 ( defaults to 1 ) :
1
Enter the Width from 1 to 20 (defaults to 1 ) :
2
Enter 1 to find Area
Enter 2 to find Perimeter
Enter 3 to quit
Choice:1
Area: 2.000000
Choice:2
Perimeter: 6.000000
Choice:3
But I am not sure how to get it to read the word area or perimeter and then on the same line take in the width and height then print out either area of perimeter as an answer until quit is entered
Here is my code:
import java.util.Scanner;
//I just put everything in one class, the Rectangle keeps its properties
//main was just added
//feel free to seperate as needbe
public class Rectangle1{
// length and width default to 1
private static double length;
private static double width;
public static double perimeter;
public static double area;
private static int choice;
//empty constructor
public Rectangle1(){
setLength(1);
setWidth(1);
}
// constructor with length and width supplied
public Rectangle1( double theLength, double theWidth) {
setLength(theLength );
setWidth( theWidth );
} // end Rectangle two-argument constructor
// validate and set length
public void setLength(double theLength){
length = ( theLength > 0.0 && theLength < 20.0 ? theLength : 1.0 );
} // end method setLength
// validate and set width
public void setWidth(double theWidth){
width = ( theWidth > 0.0 && theWidth <20.0 ? theWidth : 1.0);
}//end method setWidth
// get value of length
public double getLength(){
return length;
}//end method getLength
// get value of width
public double getWidth(){
return width;
}// end method getWidth
// calculate rectangle's perimeter
public static double calcPerimeter () {
perimeter = (length * 2) + (width * 2);//calculates area
System.out.printf("Perimeter: %f\n", perimeter);//output
return perimeter;
}
// calculate rectangle's area
public static double calcArea(){
area = (length * width);//calculates area
System.out.printf("Area: %f\n", area);//output
return area;
}
// convert to String
public String toString(){
return String.format("%s02d %02d", length, width);
}///end method toPerimeter String
public static void main( String args[] )
{
Scanner input = new Scanner (System.in);
Rectangle1 myRectangle = new Rectangle1(); //this is an object instance
int choice;
double width;
double length;
System.out.println("To find the area or perimeter of a rectangle" );
System.out.println ( "Enter the Length from 1 to 20 ( defaults to 1 ) : " );
length = input.nextInt();
System.out.println ( "Enter the Width from 1 to 20 (defaults to 1 ) : " );
width = input.nextInt();
//We need to now set these values to our rectangle object
myRectangle.setWidth(width);
myRectangle.setLength(length);
System.out.println ( "Enter 1 to find Area" );
System.out.println ( "Enter 2 to find Perimeter" );
System.out.println ( "Enter 3 to quit" );
System.out.printf ( "Choice:" );
choice = input.nextInt();
while ( choice != 3 ){
if (choice == 1){
System.out.printf( "", myRectangle.calcArea()); //call the method of our created object instance, NOT the class name
}
else if ( choice == 2){
System.out.printf( "", myRectangle.calcPerimeter());//call the method of our created object instance, NOT the class name
}
System.out.printf ( "Choice:" );
choice = input.nextInt();
}
}//end method main
} // end class Rectangle
Sorry I know the indenting is not good.
You need to ask the user for the entire question (ie {cmd} {x} {y} {width} {height}) in one go and then parse this result.
For example...
cmd = input.nextLine(); // Where cmd is a String
// example input...
// area 1 2 3 4
// perimeter 1 2 3 4
// quite
Once you have the user input, you need to parse this text. Now you could use regular expression to do this, but better to keep it simple to start with ;)
Instead, you can use what you already know...
Scanner parser = new Scanner(cmd);
cmd = parser.next();
// Example output...
// area
// perimeter
// quite
Now. Once you have the cmd (or what the user wants to do), you need to start making decisions about...
// First, we need to know if we can handle the question...
if ("area".equalsIgnoreCase(cmd) || "perimeter".equalsIgnoreCase(cmd)) {
Then you can start extracting the parameters...
int x = parser.nextInt();
int y = parser.nextInt();
int width = parser.nextInt();
int height = parser.nextInt();
Now, I'd probably also use parser.hasInt() to check that the parameter exists, but that's just me...
Then, all you need to do is stick it inside a loop...
do {
// Get user input
// Parse user input
// Make some decisions...
} while (!"quite".equalsIgnoreCase(cmd));