I'm not entirely sure if there is an easier answer to this question and I'm thinking to hard about it or what, but I'm currently programming a rectangular block program to practice Java. It's structured to have 4 methods: getInput, volBlock, saBlock, and display, and I want to use only local variables for these methods. Is there a way that I can utilize getInput to accept and return a single double from the user and if so, how can I use that input in my other methods?
I constructed this code, which uses local variables in getInput() and then passes those values to other methods, but I couldn't figure out a display method so I hard coded it into the calculation methods themselves.
Here is that code:
import java.util.*;
public class Block {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String choice = "Y";
while (choice.equals("Y")){
getInput();
System.out.println("Would you like to do another calculation?(Y/N): ");
choice = in.next().toUpperCase();
}
System.out.println("Program now ending...");
}
public static void getInput() {
double l, w, h;
Scanner fin = new Scanner(System.in);
System.out.println("Please enter the length, width, and height in that order: ");
l = fin.nextDouble();
w = fin.nextDouble();
h = fin.nextDouble();
volBlock(l, w, h);
surfaceAreaBlock(l,w,h);
}
public static void volBlock(double length, double width, double height) {
double volume;
volume = length * width * height;
System.out.println("The volume is: " + volume);
}
public static void surfaceAreaBlock (double l, double w, double h) {
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
System.out.println("The surface area is: " + surfaceArea);
}
}
I'm sorry if this question is kind of scrambled, I am having a hard time figuring all of this out. I'm quite new to Java.
Any help is appreciated, thank you!
If you're practicing java, you should probably familiarize yourself more with object oriented programming before you go any further, because your code leads me to believe that you're more used to procedural languages (e.g. C, C++, etc). Java doesn't rely on having several static helper methods in its main; the preferred approach is to construct a few classes that perform these calculations for you, and you use the results created by these functions for your basic input/output, which is normally what main is used for.
I implemented a block class to demonstrate what I mean:
public class Block {
private double length;
private double width;
private double height;
public Block(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * length * (height + width) + height * width;
}
/* This is the "display" method that you want */
public String toString() {
return "The volume is: " + getVolume() + "\n"
"The surface area is: " + getSurfaceArea();
}
}
using the Block class, your main becomes much more simple:
public static void main() {
Scanner in = new Scanner(System.in);
char choice = 'y';
do {
System.out.print("Please enter the dimensions of the block: ");
double length = in.nextDouble();
double width = in.nextDouble();
double height = in.nextDouble();
Block block = new Block(length, width, height);
System.out.println(block);
System.out.print("continue (y/n)? ");
choice = in.nextLine.toLowerCase().charAt(0);
} while (choice == 'y');
}
If you return the values from your getInput(), volBlock() and surfaceAreaBlock() methods you might be able to structure the rest as you want to.
For instance surfaceAreaBlock becomes:
public static double surfaceAreaBlock (double l, double w, double h){
double surfaceArea;
surfaceArea = 2 * (l*h+l*w+h*w);
return surfaceArea;
}
and then when you call surfaceAreaBlock you can do this:
public static void main(String[] args) {
...
double surfaceArea = surfaceAreaBlock();
// Do something with the surface area in this method
...
}
Related
I'm a beginner at Java and I'm having trouble understanding why my "Inflate" and "getVolume" methods aren't working. I'm sure they're just simple problems but I'd still like some help so I can fix my code and improve!
import java.util.Scanner;
public class Balloon
{
public static void main(String[] args)
{
Scanner multiplier = new Scanner(System.in);
System.out.println("How much should the radius be increased by? ");
double amount = multiplier.nextDouble();
double radius = 0;
public void Inflate(double amount);
{
double newRadius = radius + amount;
}
public double getVolume();
{
double sVolume = (4/3)*Math.PI*(newRadius*newRadius*newRadius);
System.out.print(sVolume);
}
}
}
I suppose that Ballon is an object you can inflate and has an state of radius, you can moreover get the volume.
The main method here is only to test if balloon works correctly
public class Balloon {
private double radius = 0;
public static void main(String[] args) {
Scanner multiplier = new Scanner(System.in);
System.out.println("How much should the radius be increased by? ");
Balloon balloon=new Balloon();
double amount = multiplier.nextDouble();
balloon.inflate(amount);
double volume = balloon.getVolume();
System.out.print(volume);
}
public void inflate(double amount) {
radius = radius + amount;
}
public double getVolume() {
double sVolume = (4 / 3) * Math.PI * (Math.pow(radius, 3));
return sVolume;
}
}
I'm having difficulty trying to print the result of the static method calcArea, which takes the int radius as parameter to calculate the area of a circle and returns the area.
Here's the code below 👇 Any help would be appreciated.
public class CircleArea {
public int radius;
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the radius of the circle: ");
int radius = input.nextInt();
System.out.print("The area of the circle is:" + calcArea()); <-- ERROR HERE
}
public static double calcArea(int radius){
double area = Math.PI * Math.pow(radius, 2);
return area;
}
}
Your call to calcArea needs a parameter passed in. Probably calcArea(radius).
The function calcArea() takes the value of radius and then returns area. To do this, you need to pass an argument to calcArea(). So, your code should be like this:
System.out.print("The area of the circle is:" + calcArea(radius));
The error you're getting clearly points out that you're missing an argument.
call method calcArea, you need give a parameter,Here are the correct example"
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the radius of the circle: ");
int radius = input.nextInt();
System.out.print("The area of the circle is:" + calcArea(radius));
}
So I've spent the last couple days working on this program, and I've hit a roadblock. I am trying to make a calculator that uses specific programs with user input to calculate the Surface area or Volume of multiple shapes. You might recognize this as project 8.5 from the Horstmann java concepts book.
I don't know how to call the methods from one file to another, and need to figure it out.
Here's the code:
import java.util.Scanner;
public class p85SantoCharlie{
public static double sphereVolume(double r){
Scanner in = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
double volume = (4/3) * Math.PI * r * r * r;
System.out.println(volume);
return volume;
}
public static double sphereSurface(double r){
Scanner in = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
double surface = 4 * Math.PI * r * r ;
System.out.println(surface);
return surface;
}
public static double cyliderVolume(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double volume = Math.PI * r * r * h ;
System.out.println(volume);
return volume;
}
public static double cylinderSurface(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double surface = 2 * Math.PI * r * r * h ;
System.out.println(surface);
return surface;
}
public static double coneVolume(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double volume = Math.PI * r * r * h / 3 ;
System.out.println(volume);
return volume;
}
public static double coneSurface(double r, double h){
Scanner in = new Scanner(System.in);
Scanner out = new Scanner(System.in);
System.out.println("Please enter your Radius");
r = in.nextDouble();
System.out.println("Please enter your Height");
h = out.nextDouble();
double surface = Math.PI * r * (r + Math.pow(( r * r + h * h), .5));
System.out.println(surface);
return surface;
}
}
And here is the main file:
import java.util.Scanner;
public class p85SantoCharlieMain{
public static void main(String[] args){
p85SantoCharlie mainProgram = new p85SantoCharlie();
Scanner in = new Scanner(System.in);
System.out.println("Please select a shape");
System.out.println("your choices are: Sphere, Cylinder, and Cone");
String answer1 = in.next();
String answer1Caps = answer1.toUpperCase();
System.out.println("Fantastic! now select a formula");
System.out.println("your choices are: surface area or volume");
String answer2 = in.next();
String answer2Caps = answer2.toUpperCase();
if (answer1Caps.equals("SPHERE")&& answer2Caps.equals("SURFACE AREA")){
mainProgram.sphereSurface();
}
}
}
Thanks!
If the methods are static you can call them using the class name
p85SantoCharlie.sphereVolume(1.1);
And if they aren't static initialize new class instance and use it to call
p85SantoCharlie p = new p85SantoCharlie();
p.sphereVolume(1.1);
Three problems:
First, all of your calculation methods in p85SantoCharlie are static. You don't need an instance of p85SantoCharlie to invoke them. You should get rid of the line where you do new p85SantoCharlie() and invoke your methods like
p85SantoCharlie.sphereVolume(r);
Second, you have declared your calculation methods as taking parameters, but you don't know those parameters when you invoke them. For example, sphereVolume() is declared as taking double r. But you don't know the value of r until you read it in within the sphereVolume() method. So that can't work. You need to change your main method to ask for the radius, then pass it to sphereVolume as shown above.
Third, all of those Scanners! Get rid of them all except for the one in main. You will be passing in the value of r (or whatever) when you invoke the calculation method. Just use what is passed in.
Ugly, unreadable code.
Java's an object-oriented language. I would expect that you'd start with a Shape interface:
public interface Shape {
double surfaceArea();
double volume();
}
I'd expect to see subclasses for different types that would do the calculation appropriately. Here's a Sphere implementation:
public class Sphere implements Shape {
private final double radius;
public Sphere(double radius) {
if (radius <= 0.0) throw new IllegalArgumentException("radius must be positive");
this.radius = radius;
}
public double surfaceArea() {
return 4.0*Math.PI*this.radius*this.radius;
}
public double volume() {
return 4.0*Math.PI*this.radius*this.radius*this.radius/3.0;
}
}
Here's a Cylinder implementation:
public class Cylinder implements Shape {
private final double radius;
private final double height;
public Cylinder(double radius, double height) {
if (radius <= 0.0) throw new IllegalArgumentException("radius must be positive");
if (height <= 0.0) throw new IllegalArgumentException("height must be positive");
this.radius = radius;
this.height = height;
}
public double surfaceArea() {
return 2.0*Math.PI*this.radius*this.radius + this.radius*this.height;
}
public double volume() {
return Math.PI*this.radius*this.radius*this.height;
}
}
I'd expect to see your driver class interact with Shape objects to solve the problem.
You'll want to consider a virtual constructor/factory for Shape, because you won't want to clutter your code with if/else constructs.
My opinion: Object-oriented programming was invented to solve two problems:
Encapsulation of state and behavior into a single abstract data type.
Inheritance and polymorphism to eliminate if/else and switch statements.
Do not clutter your code with "if sphere and area" kinds of decisions. Let polymorphism handle it for you.
New programmers tend to spend too much time worrying about user interfaces. Concentrate on the functionality and get that working first. Don't create a bunch of text question/answer code and leave the meat of the problem undone.
The assignment goes as stated:
The problem
The westfield carpet company has asked you to write an application that calculates the price of carpeting for rectangular rooms. To calculate the price, you multiply the area of the floor(width times length) by the price per square foot of carpet. For example, the area of floor that is 12 feet long and 10 feet wide is 120 square feet. To cover that floor with carpet that costs $8 per square foot would cost $960 (12x10x8=960)
First, you should create a class named RoomDimension that has two Feields: one for the lenght of the room and one for the width. The RoomDimension class should have a method that returns the area of the room (the area of the room is the room's length multiplied by the room's width).
Next, you should create a RoomCarpet class that has a RoomDimension object as a field. It should also have a field for the cost of the carpet per square foot. The RoomCarpet class should have a method that returns the total cost of the carpet.
Once you have written these classes, use them in an application that asks the user to enter the dimensions of a room and the price per square foot of the desired carpeting. The application should display the total cost of the carpet.
The code I have below can't seem to run due to an error in the 31st line of the MainProgram
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
final double CARPET_PRICE_PER_SQFT = 8.0;
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Display intro.
System.out.println("This program will display the "
+ "carpet cost of a room." + "\nPlease enter the room's "
+ "dimension in feet.");
// Get the length of the room.
System.out.print("Enter the length of room: ");
double length = keyboard.nextDouble();
// Get the width of the room.
System.out.print("Enter the width of room: ");
double width = keyboard.nextDouble();
//close keyboard
keyboard.close();
****// Create RoomDimension and RoomCarpet objects.
CarpetCalculatorProgram calculatorProgram = new CarpetCalculatorProgram();
RoomDimension dimensions = calculatorProgram.new RoomDimension(length,
width);
RoomCarpet roomCarpet = calculatorProgram.new RoomCarpet(dimensions,
CARPET_PRICE_PER_SQFT);****
// Print the object calling the toString
System.out.println(roomCarpet);
}
}
Here are the other classes for the code:
Room Dimension
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class RoomDimension {
private double length;
private double width;
public RoomDimension(double length, double width) {
super();
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getArea() {
return length * width;
}
#Override
public String toString() {
return "RoomDimension [length=" + length + ", width=" + width + "]";
}
}
Room Carpet
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class RoomCarpet {
private RoomDimension roomDimensions;
private double costOfCarpet;
public RoomCarpet(RoomDimension roomDimensions, double costOfCarpet) {
super();
this.roomDimensions = roomDimensions;
this.costOfCarpet = costOfCarpet;
}
public double getTotalCost() {
return costOfCarpet * roomDimensions.getArea();
}
#Override
public String toString() {
return "RoomCarpet [roomDimensions=" + roomDimensions
+ ", costOfCarpet=" + costOfCarpet + ", "
+ "total cost=" + getTotalCost() + "]";
}
}
The error I get when I paste all the things into my IDE is
CarpetCalculatorProgram cannot be resolved to a type
Assuming that there are no classes you didn't post:
There is no CarpetCalculatorProgram class and there are no inner RoomDimension / RoomCarpet classes in there. RoomDimension is actually an independent top level class. The code must either be
// Create RoomDimension and RoomCarpet objects.
RoomDimension dimensions = new RoomDimension(length,
width);
RoomCarpet roomCarpet = new RoomCarpet(dimensions,
CARPET_PRICE_PER_SQFT);
instead of using new EnclosingClass().new InnerClass() syntax. OR
// Create RoomDimension and RoomCarpet objects.
CarpetCalculatorProgram calculatorProgram = new CarpetCalculatorProgram();
CarpetCalculatorProgram.RoomDimension dimensions = calculatorProgram.new RoomDimension(length,
width);
CarpetCalculatorProgram.RoomCarpet roomCarpet = calculatorProgram.new RoomCarpet(dimensions,
CARPET_PRICE_PER_SQFT);
AND the two classes moved into the CarpetCalculatorProgram class:
public class CarpetCalculatorProgram {
public class RoomDimension {
...
}
public class RoomCarpet {
...
}
}
Well my code is working properly, see if it helps you.
import java.util.Scanner;
class RoomDimension{
private int length;
private int width;
public RoomDimension(int length, int width){
this.length= length;
this.width= width;
}
public int Area(){
int area= this.length* this.width;
return area;
}
public int getlength(){
return this.length;
}
public int getwidth(){
return width;
}
}
class RoomCarpet{
private RoomDimension RD;
private int costperSq;
public RoomCarpet(RoomDimension RD, int costperSq){
this.RD= RD;
this.costperSq= costperSq;
}
public int TotalCost(){
return this.costperSq* RD.Area();
}
}
[Main]
class Main{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("enter the length the room");
int L= sc.nextInt();
System.out.println("enter the width the room");
int W= sc.nextInt();
RoomDimension RD= new RoomDimension(L, W);
System.out.println("enter how much the carpet costs per sq");
int cost= sc.nextInt();
RoomCarpet RC= new RoomCarpet(RD, cost);
System.out.println("total cost of the carpet will be= "+RC.TotalCost());
}
}
How do i call the length and width variable into the getArea method without creating a private variable in the class, the way I'm doing it is causing the method to run again after its already ran once. I really don't like it this way but thats the way the professor wants it done to simulate the times before "object oriented programming"
/*This program allows the user to enter the length and widtch and receive the area
of the rectangle*/
import java.util.Scanner;
public class theRectangleCompany
{
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getLength();
getWidth();
getArea();
}
public static double getLength()
{
double length;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the length ");
length = keyboard.nextDouble();
return length;
}
public static double getWidth()
{
double width;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the width ");
width = keyboard.nextDouble();
return width;
}
public static void getArea()
{
double length = getLength();
double width = getWidth();
double area = width * length;
System.out.println("The area of the Rectangle is: " +area);
}
}
Why are you calling getLength() and getWidth() from the main method. Just call getArea()
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
You could make the getArea function take parameters, and use the function calls to the other two functions as the parameters:
getArea(getLength(), getWidth());
public static void getArea(double length, double width) { ... }
changes are here:
/*This program allows the user to enter the length and widtch and receive the area
of the rectangle*/
import java.util.Scanner;
public class theRectangleCompany
{
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
public static double getLength()
{
double length;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the length ");
length = keyboard.nextDouble();
return length;
}
public static double getWidth()
{
double width;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the width ");
width = keyboard.nextDouble();
return width;
}
public static void getArea()
{
double length = getLength();
double width = getWidth();
double area = (width * length);
System.out.println("The area of the Rectangle is: " +area);
}
}
Not sure if this is what you want:
public static void getArea()
{
System.out.println("The area of the Rectangle is: " + (getLength() * getWidth()));
}
You'd also need to change the main method to exclude the getLength() and getWidth():
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea();
}
An variant to the above is something like
public static void main(String[] args)
{
System.out.print("This program will find an area of a Rectangle ");
getArea(getLength(),getWidth());
}
public static void getArea(double length, double width)
{
System.out.println("The area of the Rectangle is: " + (length * width));
}