Trying to use an Instance variable from a void method (java) - java

I'm currently writing a code that asks for a packages dimensions then uses the volume to calculate the shipping costs. There is another class that I have not included in the post which handles the cost calculation. I currently at a loss for how to take the input of the inputLength etc. methods and put them into the Package and Package copy methods. And also why i cant use them in the calcVolume and displayDimensions methods.
import java.util.Scanner;
public class Package {
private double length;
private double width;
private double height;
private Scanner input = new Scanner(System.in);
public Package() {
double length = 1.0;
double width = 1.0;
double height = 1.0;
}
public static void main(String[] args) {
System.out.printf("Welcome to Colin's Shipping Calculator!%n%n");
System.out.printf("Enter first package dimensions%n");
Package volCalc;
volCalc = new Package();
volCalc.inputLength();
volCalc.inputWidth();
volCalc.inputHeight();
System.out.printf("Enter second package dimensions%n");
volCalc.inputLength();
volCalc.inputWidth();
volCalc.inputHeight();
volCalc.displayDimensions();
volCalc.calcVolume();
Shipment shipCalc = new Shipment();
shipCalc.inputPackage();
shipCalc.inputPackage();
shipCalc.calculateCost();
shipCalc.display();
}
public Package(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public Package(Package copy) {
Package newPackage = new Package();
newPackage.length = copy.length;
newPackage.width = copy.width;
newPackage.height = copy.height;
}
public void inputLength() {
System.out.printf("Enter Length: ");
double length = input.nextDouble();
}
public void inputWidth() {
System.out.printf("Enter Width: ");
double width = input.nextDouble();
}
public void inputHeight() {
System.out.printf("Enter Height: ");
double height = input.nextDouble();
}
public void displayDimensions() {
System.out.printf(length + " X " + width + " X " + height);
}
public double calcVolume() {
double volume = length*width*height;
System.out.printf("%nVolume: " + volume);
return volume;
}

You are shadowing your member variables by declaring them again in the methods. Try removing the 'double' before the variable name in the functions.
Here an example. I also changed every printf statement to either print or println. But I'm not sure how Shipment should work.
import java.util.Scanner;
public class Package {
private double length;
private double width;
private double height;
private Scanner input = new Scanner(System.in);
public Package() {
this.length = 1.0; // Removed 'double'
this.width = 1.0;
this.height = 1.0;
}
public static void main(String[] args) {
System.out.println("Welcome to Colin's Shipping Calculator!\n");
System.out.println("Enter first package dimensions");
Package packageA;
packageA = new Package();
packageA.inputLength();
packageA.inputWidth();
packageA.inputHeight();
packageA.displayDimensions();
packageA.calcVolume();
System.out.println("Enter second package dimensions");
Package packageB = new Package(); // New Package
packageB.inputLength();
packageB.inputWidth();
packageB.inputHeight();
packageB.displayDimensions();
packageB.calcVolume();
Shipment shipCalc = new Shipment();
shipCalc.inputPackage();
shipCalc.inputPackage();
shipCalc.calculateCost();
shipCalc.display();
}
public Package(double length, double width, double height) {
this.length = length; //'this' needed else shadowing occurs
this.width = width;
this.height = height;
}
public Package(Package copy) {
// Package newPackage = new Package(); Not needed
this.length = copy.length; // 'this' just for clarification.
this.width = copy.width;
this.height = copy.height;
}
public void inputLength() {
System.out.print("Enter Length: ");
length = input.nextDouble(); // Removed 'double'
}
public void inputWidth() {
System.out.print("Enter Width: ");
width = input.nextDouble(); // Removed 'double'
}
public void inputHeight() {
System.out.print("Enter Height: ");
height = input.nextDouble(); // Removed 'double'
}
public void displayDimensions() {
System.out.println(length + " X " + width + " X " + height);
}
public double calcVolume() {
double volume = length * width * height;
System.out.println("Volume: " + volume);
return volume;
}
}

Related

myRectangle.calculateArea(); returns error "package myRectangle does not exist"

Rectangle
public class Rectangle {
private double width;
private double length;
public Rectangle(double L, double W){
length = L;
width = W;
}
public void setLength(double Length){
if (length>=0 && length <=20)
length = Length;
else{
length = 0;
}
}
public double getLength(){
return length;
}
public void setWidth(double Width){
if (width>=0 && length <=20)
width = Width;
else{
width = 0;
}
}
public double getWidth(){
return width;
}
public void calculatePerimeter(){
System.out.println("The perimeter of rectangle is: " + 2 * (length + width));
}
public void calculateArea(){
System.out.println("The area of the rectangle is: " + (length * width));
}
}
TestRectangle
import java.util.Scanner;
public class TestRectangle {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Rectangle myRectangle = new Rectangle (0,0);//I did the same thing in a
//previous assignment, and someone else who did this assignment (code found
//online) also did this. It worked before but seems useless now?
System.out.println("Enter length: ");
double L = input.nextDouble();
System.out.println();
System.out.println("Enter width: ");
double W = input.nextDouble();
System.out.println();
}
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
//<identifier> expected, package myRectangle does not exist
}
I am trying to create a program "Rectangle" to calculate the area and perimeter of a rectangle, and then create a test program to run program "Rectangle"
I have copied code from a previous assignment called "Date", where the basic idea is similar, but when I get to the end of the program where I need to call on "calculateArea();" and "calculatePerimeter();" in the test program, I get an error telling me that package myRectangle doesn't exist.... can someone tell me why this is happening? A similar code worked in the previous assignment, and I found someone else's code for the same "Rectangle" program and it shows the same error. Did I do something wrong or is there something wrong with my NetBeans?
This is the code I based the Rectangle and TestRectangle program off of
Date
public class Date {
private int month;
private int day;
private int year;
public Date(int m, int d, int y){
month = m;
day = d;
year = y;
}
public void setMonth(int Months){
if(Months>=0 && Months <= 12)
month=Months;
else{
month=0;
}
}
public int getMonth(){
return month;
}
public void setDay(int Days){
if(Days>= 0 && Days<=31)
day = Days;
else{
day=0;
}
}
public int getDay(){
return day;
}
public void setYear(int Years){
year=Years;
}
public int getYear(){
return year;
}
public void displayDate(){
System.out.printf
("%d/%d/%d\n", getMonth(), getDay(), getYear() );
}
}
TestDate
import java.util.Scanner;
public class DateTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Date myDate = new Date(0,0,0);
System.out.println("Justine Dodge, assignment 6\n");
System.out.println("Please enter month: ");
int m = input.nextInt();
myDate.setMonth(m);
System.out.println();
System.out.println("Enter day: ");
int d = input.nextInt();
myDate.setDay(d);//assign d to Day?
System.out.println();//output blank line
System.out.println("Enter year: ");
int y = input.nextInt();
myDate.setYear(y);
System.out.println();
myDate.displayDate();
}
}
in the TestRectangle you are closing the main method before calling these functions
} // this should be at at the end of the main function
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
i.e
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
}
This will remove the compilation error. Now when you run it , you will get both area and perimeter as 0 because in the constructor , you are passing values of length and width as 0 and not really using the length and width taken as input.
To resolve this issue, insstead of passing 0,0 in constructor,
try to pass L,W in constructor like this
Rectangle myRectangle = new Rectangle (L,W);
myRectangle.getLength()); //
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();
import java.util.Scanner;
public class TestRectangle {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
// Rectangle myRectangle = new Rectangle (0,0);//I did the same thing in a
//previous assignment, and someone else who did this assignment (code found
//online) also did this. It worked before but seems useless now?
System.out.println("Enter length: ");
double L = input.nextDouble();
System.out.println();
System.out.println("Enter width: ");
double W = input.nextDouble();
System.out.println();
Rectangle myRectangle = new Rectangle (L,W);
// System.out.println("get length " + myRectangle.getLength());
myRectangle.calculateArea();//here
myRectangle.calculatePerimeter();//and here is where I get the error
//<identifier> expected, package myRectangle does not exist
}
}
then you will get o/p like this

How to correctly code max, min, and avg in this code?

I cannot figure out why my code is:
giving me a null output
not calculating the max, min values, and average values.
There are two classes in my code, and I'm supposed to find the average, max, and min of a set of values.
public class CirclesV8
{
//declaration of private instance variables
private double myRadius, mySphere;
private double myArea = 0, total = 0;
//instance variables for totals average
private double MyTotal = 0;
private double MyAverage = 0;
//constructor for objects of type CirclesV8
public CirclesV8(int r, int s)
{
myRadius = r;
mySphere = s;
MyTotal = total;
}
//getter method for radius and total
public double getRadius()
{
return myRadius;
}
public double getSphere()
{
return mySphere;
}
public double getTotal()
{
return MyTotal;
}
//mutator method for the area, average, and circumference
public void calcArea()
{
myArea = Math.PI * (Math.pow(myRadius, 2));
}
public double getArea()
{
return myArea;
}
public void calcSurfaceArea()
{
mySphere = (Math.pow(myRadius, 2)) * Math.PI * 4;
}
public double getSurfaceArea()
{
return mySphere;
}
public void calcAvg()
{
MyAverage = MyTotal / 5;
}
public double getAvg()
{
return MyAverage;
}
//setter method for myTotal
public void setTotal(double total)
{
MyTotal = total;
}
// returns a String of the object's values. The format() method is similar to printf().
public String toString()
{
return String.format("%12d %14.1f %13.1f 12.1f", myRadius,
myArea,
mySphere,
MyAverage);
}
}
import java.util.Scanner;
public class V8Tester
{
public static void main(String[] args)
{
//create scanner object
Scanner in = new Scanner(System.in);
//initialize variables
int radius1, radius2, radius3, radius4, radius5;
int sphere1, sphere2, sphere3, sphere4, sphere5;
double Average = 0;
double total = 0;
double min = Integer.MAX_VALUE;
double max = Integer.MIN_VALUE;
System.out.println("Please enter five radiuses separate by space (ex. 6 12)");
radius1 = in.nextInt();
radius2 = in.nextInt();
radius3 = in.nextInt();
radius4 = in.nextInt();
radius5 = in.nextInt();
System.out.println("Please enter another 5 radiuses separate by space (ex. 6 12)");
sphere1 = in.nextInt();
sphere2 = in.nextInt();
sphere3 = in.nextInt();
sphere4 = in.nextInt();
sphere5 = in.nextInt();
//Create array of objects
CirclesV8 [] circles = {new CirclesV8(radius1, sphere1),
new CirclesV8(radius2, sphere2),
new CirclesV8(radius3, sphere3),
new CirclesV8(radius4, sphere4),
new CirclesV8(radius5, sphere5)};
//call methods
for(int index = 0; index < circles.length; index++)
{
circles[index].calcArea();
circles[index].calcSurfaceArea();
circles[index].calcAvg();
//store totals for calculating average
total += circles[index].getTotal();
//calc max and min
if(circles[index].getTotal() < min)
min = circles[index].getTotal();
if(circles[index].getTotal() > max)
max = circles[index].getTotal();
}
//set total values & call average methods to calculate averages using one of the objects
circles[4].setTotal(total);
circles[4].calcArea();
circles[4].calcSurfaceArea();
circles[4].getAvg();
//Circle Colors
System.out.println("Color of Circle #1: ");
String circle1 = in.next();
System.out.println("Color of Circle #2: ");
String circle2 = in.next();
System.out.println("Color of Circle #3: ");
String circle3 = in.next();
System.out.println("Color of Circle #4: ");
String circle4 = in.next();
System.out.println("Color of Circle #5: ");
String circle55 = in.next();
String[] array = new String[5];
array[0] = circle1;
array[1] = circle2;
array[2] = circle3;
array[3] = circle4;
array[4] = circle55;
//Sphere Colors
System.out.println("Color of Sphere #1: ");
String sphere11 = in.next();
System.out.println("Color of Sphere #2: ");
String sphere22 = in.next();
System.out.println("Color of Sphere #3: ");
String sphere33 = in.next();
System.out.println("Color of Sphere #4: ");
String sphere44 = in.next();
System.out.println("Color of Sphere #5: ");
String sphere55 = in.next();
String[] arr = new String[5];
array[0] = sphere11;
array[1] = sphere22;
array[2] = sphere33;
array[3] = sphere44;
array[4] = sphere55;
int i = 1;
System.out.println(" Color Radius Surface Area Area");
System.out.println("==============================================================");
for(int index = 0; index < circles.length; index++)
{
System.out.printf("%4s %10.1f %14.1f%n", array[index],
circles[index].getRadius(),
circles[index].getArea(),
i++);
}
public class CirclesV8
{
//declaration of private instance variables
private double myRadius, mySphere;
private double myArea = 0, total = 0;
//instance variables for totals average
private double MyTotal = 0;
private double MyAverage = 0;
//constructor for objects of type CirclesV8
public CirclesV8(int r, int s)
{
myRadius = r;
mySphere = s;
MyTotal = total;
}
//getter method for radius and total
public double getRadius()
{
return myRadius;
}
public double getSphere()
{
return mySphere;
}
public double getTotal()
{
return MyTotal;
}
//mutator method for area, average, and circumference
public void calcArea()
{
myArea = Math.PI * (Math.pow(myRadius, 2));
}
public double getArea()
{
return myArea;
}
public void calcSurfaceArea()
{
mySphere = (Math.pow(myRadius, 2)) * Math.PI * 4;
}
public double getSurfaceArea()
{
return mySphere;
}
public void calcAvg()
{
MyAverage = MyTotal / 5;
}
public double getAvg()
{
return MyAverage;
}
//setter method for myTotal
public void setTotal(double total)
{
MyTotal = total;
}
// returns a String of the object's values. The format() method is similar to printf().
public String toString()
{
return String.format("%12d %14.1f %13.1f 12.1f", myRadius,
myArea,
mySphere,
MyAverage);
}
}
This gives me a null output
for(int index = 0; index < circles.length; index++)
{
System.out.printf("%4s %10.1f %20f", arr[index],
circles[index].getRadius(),
circles[index].getSurfaceArea(),
i++);
}
System.out.println("==============================================================");
I can't get this to print values
System.out.printf("%20s%n", "Minimum: ", max);
System.out.printf("%20s%n", "Maximum: ", min);
System.out.printf("%20s%n", "Average: ", circles[4].getAvg());
}
}

Getting an error when trying to run my last method

My program requires me to create 4 methods. 1 to take in length, 1 to take width, and 1 to calculate the area, and 1 to display the area. My code seems to be working up till the final method where i need to display my area. I've tried pretty much almost everything i can think of but it still isn't working.
import java.io.*;
import java.util.*;
public class Lab9Q2
{
public static double getLength()
{
Scanner keyboard = new Scanner (System.in); // Create Method
System.out.println ("Enter the length of the rectange"); // ask for the length
double length = keyboard.nextDouble();
return length;
}
public static double getWidth()
{
Scanner keyboard = new Scanner (System.in); // Create Method
System.out.println ("Enter the width of the rectange"); // ask for the width
double width = keyboard.nextDouble();
return width;
}
public static double getArea (double length, double width)
{
double area;
area = length*width;
return area;
}
public static double displayArea (double length, double width, double area)
{
System.out.println ("The length is: " + length);
System.out.println ("The width is: " + width);
System.out.println ("The area of the rectangle is: " + area);
}
public static void main (String [] args)
{
getLength();
getWidth();
displayArea(length, width, area);
}
}
The program should use all my method calls and then display the results properly but it wont do so.
You probably intended to use the three results from the helper methods in the final call to displayArea():
public static void main (String[] args) {
double length = getLength();
double width = getWidth();
double area = getArea(length, width);
displayArea(length, width, area);
}
Change the main block as below
public static void main(String [] args) {
double length = getLength();
double width = getWidth();
double area = getArea(length, width);
displayArea(length, width, area);
}
You missed the assignments and calling getArea function
Two ways you can get your code working
1) change your main method as
public static void main (String[] args) {
double length = getLength();
double width = getWidth();
double area = getArea(length, width);
displayArea(length, width, area);
}
2) Declare your length,width,area globally.
import java.io.*;
import java.util.*;
public class Lab9Q2
{
public static double length;
public static double width;
public static double area;
public static void getLength()
{
Scanner keyboard = new Scanner (System.in); // Create Method
System.out.println ("Enter the length of the rectange"); // ask for the length
length = keyboard.nextDouble();
}
public static void getWidth()
{
Scanner keyboard = new Scanner (System.in); // Create Method
System.out.println ("Enter the width of the rectange"); // ask for the width
width = keyboard.nextDouble();
}
public static void getArea (double length, double width)
{
area = length*width;
}
public static double displayArea (double length, double width, double area)
{
System.out.println ("The length is: " + length);
System.out.println ("The width is: " + width);
System.out.println ("The area of the rectangle is: " + area);
}
public static void main (String [] args)
{
getLength(); //Here length will get initialised
getWidth(); //Here width will get initialised
getArea(); //Here area will get calculated ..you also missed this statement
displayArea(length, width, area);
}
}

How to Calculate BMI in Java

I'm writing a program that takes the users input for height and weight then calculates the Body Mass Index from this. It uses separate methods for height, weight and BMI, these methods are called from main. The problem I'm having is I have absolutely no clue how to put the input from weight and height methods into the BMI method. This is what the code looks like:
public class BMIProj {
static Scanner input = new Scanner(System.in);
public static int heightInInches()
{
System.out.println("Input feet: ");
int x;
x = input.nextInt();
System.out.println("Input Inches: ");
int y;
y = input.nextInt();
int height = x * 12 + y;
return height;
}
public static int weightInPounds()
{
System.out.println("Input stone: ");
int x;
x = input.nextInt();
System.out.println("Input pounds ");
int y;
y = input.nextInt();
int weight = x * 14 + y;
return weight;
}
public static void outputBMI()
{
}
public static void main(String[] args) {
heightInInches();
weightInPounds();
outputBMI();
}
Thanks in advance.
I advise you to do a little bit more learning in java, specifically variables, declaring, initializing, etc.. Also learn class, constructors, etc..
You need fields for the class to save the inputed variables
I created a constructor to initialize the variables
You don't need to return anything in the methods if all you are doing is assigning values to your class fields and outputting info.
I did the curtsy of calculating the bmi for you
Anyway
public class BMIProj {
static Scanner input = new Scanner(System.in);
// Class vars
int height;
int weight;
double bmi;
//Constructor
public BMIPrj(){
//Initialize vars
height = 0;
weight = 0;
bmi = 0;
}
public static void heightInInches()
{
System.out.println("Input feet: ");
int x;
x = input.nextInt();
System.out.println("Input Inches: ");
int y;
y = input.nextInt();
int height = x * 12 + y;
return height;
}
public static void weightInPounds()
{
System.out.println("Input stone: ");
int x;
x = input.nextInt();
System.out.println("Input pounds ");
int y;
y = input.nextInt();
int weight = x * 14 + y;
return weight;
}
public static void outputBMI()
{
System.out.println("BMI: " + (( weight / height ) x 703));
}
public static void main(String[] args) {
heightInInches();
weightInPounds();
outputBMI();
}
You can assign the output of a method to a parameter like so:
int weight = weightInPounds();
When calling a method, you can pass in parameters:
outputBMI(weight);
The rest is up to you.

gives me this error: Exception in thread "main" java.lang.NoSuchMethodError: Triangle.<init>(DD)V at testTriangle.main(testTriangle.java:6)

First the error was that the variables in the parameters of the object is not initialized. Then it started to give this error when initialized, Exception in thread "main" java.lang.NoSuchMethodError: Triangle.(DD)V
at testTriangle.main(testTriangle.java:6). Please help!
// main class
import java.util.Scanner;
public class testTriangle{
public static void main(String [] args){
double xcoord = 0,ycoord = 0;
Scanner scan = new Scanner(System.in);
Triangle object = new Triangle(xcoord,ycoord);
System.out.println("Welcome to the hypothenuse finder!");
System.out.println("Please input the first value(x): ");
xcoord = scan.nextDouble();
System.out.println("Please input the second value(y): ");
ycoord = scan.nextDouble();
object.radi();
object.toString();
}
}
import java.lang.Math.*;
public class Triangle{
double x;
double y;
public Triangle(double xcoord,double ycoord){
x = xcoord;
y = ycoord;
}
public double radi(){
return(Math.sqrt(Math.pow(x,2)+Math.pow(y,2)));
}
public void toString(){
System.out.printf("The x value is: " + x + " the y value is: " + y + " and the radius is : ", radi());
}
}
I have got your code to work, by putting the 2 classes into there own class files and I also changed this method toString() name, because there is already a built in method called toString(). So I changed it to string() and it seems to work.
TestTriangle Class:
import java.util.Scanner;
public class TestTriangle{
public static void main(String [] args){
double xcoord = 0,ycoord = 0;
Scanner scan = new Scanner(System.in);
Triangle object = new Triangle(xcoord,ycoord);
System.out.println("Welcome to the hypothenuse finder!");
System.out.println("Please input the first value(x): ");
xcoord = scan.nextDouble();
System.out.println("Please input the second value(y): ");
ycoord = scan.nextDouble();
object.radi();
object.string();
}
}
Triangle Class:
public class Triangle {
double x;
double y;
public Triangle(double xcoord,double ycoord){
x = xcoord;
y = ycoord;
}
public double radi(){
return(Math.sqrt(Math.pow(x,2)+Math.pow(y,2)));
}
public void string(){
System.out.printf("The x value is: " + x + " the y value is: " + y + " and the radius is : ", radi());
}
}

Categories

Resources