I want to create a program in Java, which -- basing on user inputs -- finds the area of the entered shape. But I failed to achieve that.
This is my script:
import java.util.Scanner;
public class area {
static Scanner advance = new Scanner(System.in);
public void main(String[] args) {
nu();
}
int length;
int height;
int area;
public void nu(){
String message = advance.nextLine();
if (message.equalsIgnoreCase("rectangle")){
System.out.println("Enter the length of the rectangle: ");
length = advance.nextInt();
//length declared.//
System.out.println("Enter the height of the rectangle");
height = advance.nextInt();
//Height has been declared.//
area = length * height;
System.out.print("The area is: " + area);
}
}
}
First problem is, that this code is not running and so I don't know if its working. All the other things are fine. Can you tell me, what I'm doing wrong?
You need to add static to the main method and create a new instance of area. See the code below.
public class area {
static Scanner advance = new Scanner(System.in);
public static void main(String[] args) {
new area().nu();
}
int length;
int height;
int area;
public void nu(){
String message = advance.nextLine();
if (message.equalsIgnoreCase("rectangle")){
System.out.println("Enter the length of the rectangle: ");
length = advance.nextInt();
//length declared.//
System.out.println("Enter the height of the rectangle");
height = advance.nextInt();
//Height has been declared.//
area = length * height;
System.out.print("The area is: " + area);
}
}
}
You need to add static to the main method of your program.
You won't be able to directly call the nu() method from the main, as it is instance method to call it you will need to create an object of your class.
public static void main(String[] args) {
area a = new area();
a.nu();
}
The other alternate is that you can make your nu() method to be static but then you will not be able to use int length;int height;int area; instance variables directly in your static method nu(). Then you will either need to make these variables to be static too or create an object of the class and then use these variables as per your need.
Because of Java program can't find the main method to run:
We need to add static keyword in 3 places according to your code.
Please try with below full source code:
import java.util.Scanner;
public class area {
static Scanner advance = new Scanner(System.in);
public static void main(String[] args) { //1st change
nu();
}
static int length; //2nd change
static int height; //2nd change
static int area; //2nd change
public static void nu(){ //3rd change
String message = advance.nextLine();
if (message.equalsIgnoreCase("rectangle")){
System.out.println("Enter the length of the rectangle: ");
length = advance.nextInt();
//length declared.//
System.out.println("Enter the height of the rectangle");
height = advance.nextInt();
//Height has been declared.//
area = length * height;
System.out.print("The area is: " + area);
}
}
}
Related
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
...
}
Let's say you've calculated both the length and width of a floorboard and worked out the room area, how would you go about multiplying 10% to the room area to work out the wastage in order to obtain the final total area of the floorboard?
This is what I have done so far:
import java.util.Scanner;
class Floor1 {
public static void floor1(String[] args) {
obtainLength();
obtainWidth();
obtainRoomArea(length, width);
obtainFinalResult();
System.exit(0);
}
public static void obtainLength ()
Scanner in = new Scanner(System.in);
System.out.println("Enter length of room:");
float length = in.nextFloat();
}
public static void obtainWidth ()
Scanner in = new Scanner(System.in);
System.out.println("Enter width of room:");
float width = in.nextFloat();
}
public static void obtainRoomArea (float Length, float Width){
float RoomArea = RoomArea(Length, Width);
System.out.println("Area of room is:" + RoomArea);
}
public static void obtainFinalResult()
final double total = 0.1;
wastage =(float RoomArea* final double total);
System.out.println("The total calculations including wastage is:" + wastage);
}
}
I am only retrieving the area of the room. I'm unable to retrieve the final results. Could you please show me where I'm going wrong with examples please? Many thanks!!
I'm having trouble using non static methods. I'm trying to get the value of my "side" variable from a method and plug them into another method which will calculate area. Is there a way to do this without changing the methods to static? None of the previously answered questions on here are helping and neither is my textbook.
import java.util.*;
public class CubeVolume
{
int side1;
int side2;
int side3;
public void getSides()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the length of side1");
side1 = input.nextInt();
System.out.println("Enter the length of side2");
side2 = input.nextInt();
System.out.println("Enter the length of side3");
side3 = input.nextInt();
}
public int getVolume(int side1, int side2, int side3)
{
int volume = side1 * side2 * side3;
return volume;
}
public static void main(String[] args)
{
CubeVolume cube = new CubeVolume();
cube.getSides();
cube.getVolume(side1, side2, side3);
}
}
I think the problem is with my method call cube.getVolume(side1, side2, side3); because the compiler tells me that non-static variable cannot be referenced from a static context.
If you want to use methods within main() then those methods must be static since main() is static. So you methods should be declared as:
public static void getSides() { .... }
public static int getVolume(int side1, int side2, int side3) { .... }
You can however avoid all this if you tell an instance of your class to start from a non-static method from within your main() method:
public static void main(String[] args) {
new CubeVolume().startApp(args);
}
private void startApp(String[] args) {
CubeVolume cube = new CubeVolume();
cube.getSides();
cube.getVolume(side1, side2, side3);
}
Now your other methods in the class do not need to be static since you're not calling them from static main().
There is no need to pass in any parameters to getVolume(), just use the class variables:
import java.util.Scanner;
class CubeVolume {
private int side1;
private int side2;
private int side3;
private void getSides() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the length of side1: ");
side1 = input.nextInt();
System.out.print("Enter the length of side2: ");
side2 = input.nextInt();
System.out.print("Enter the length of side3: ");
side3 = input.nextInt();
input.close();
}
private int getVolume() {
return side1 * side2 * side3;
}
private void printAppTitle() {
System.out.println("Cube Volume Calculator");
System.out.println("======================");
}
public static void main(String[] args) {
CubeVolume cube = new CubeVolume();
cube.printAppTitle();
cube.getSides();
String cubeVolumeString = String.valueOf(cube.getVolume());
System.out.println("The cubes volume is: " + cubeVolumeString);
}
}
Example Usage:
Cube Volume Calculator
======================
Enter the length of side1: 3
Enter the length of side2: 4
Enter the length of side3: 5
The cube's volume is: 60
Alternative approach which stores the side lengths in a double array, sides, and deals with possible invalid input in getSides():
import java.util.Scanner;
class CubeVolume {
private double[] sides;
CubeVolume() {
sides = new double[3];
}
private void getSides() {
Scanner scanner = new Scanner(System.in);
int currentSide = 0;
while (currentSide < sides.length) {
System.out.printf("Enter the length of side %d: ", currentSide + 1);
double nextSide = 0.0;
input:
while (scanner.hasNext()) {
if (scanner.hasNextDouble()){
nextSide = scanner.nextDouble();
if (nextSide > 0) {
sides[currentSide] = nextSide;
break input;
} else {
System.out.println("ERROR: Input number was too small.");
System.out.printf("Enter the length of side %d: ", currentSide + 1);
}
} else {
System.out.println("ERROR: Invalid input, please input a number.");
System.out.printf("Enter the length of side %d: ", currentSide + 1);
scanner.next();
}
}
currentSide++;
}
scanner.close();
}
private double getVolume() {
return sides[0] * sides[1] * sides[2];
}
private void printAppTitle() {
System.out.println("Cube Volume Calculator");
System.out.println("======================");
}
public static void main(String[] args) {
CubeVolume cube = new CubeVolume();
cube.printAppTitle();
cube.getSides();
String cubeVolumeString = String.format("%.2f", cube.getVolume());
System.out.println("The cube's volume is: " + cubeVolumeString);
}
}
Example Usage 2:
Cube Volume Calculator
======================
Enter the length of side 1: a
ERROR: Invalid input, please input a number.
Enter the length of side 1: -1.1
ERROR: Input number was too small.
Enter the length of side 1: 3.4
Enter the length of side 2: 4.7
Enter the length of side 3: 5.8
The cube's volume is: 92.68
You need not to pass sides parameters to get valume function because your sides variable will be available to get valume function.
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));
}
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));
}