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.
Related
This assignment is to calculate the cost of a hospital visit. I am trying to ask the user what the prices for the "overnightCharge", "medicationCharge", and "labCharge" are. I then try to use the input to add them together in the method called "total". Next, I try to print the resulting/returned variable from "total" method in the main method by typing System.out.println("Your total charge is: " + total(totalCost). I thought total(totalCost) would retrieve the variable returned by "total" method.
package hospitalstay;
import java.util.Scanner;
/* total charges
if overnight charges
medication charges
lab charges
ask user if new patient*/
public class HospitalStay {
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(totalCost); // i want to print the "totalCost variable" returned by the "total" method.
}
public static double overnightCharge () {// asking user for overnight charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your overnight charge");
double overnightCharge;
overnightCharge = sc.nextDouble();
return overnightCharge;
}
public static double medicationCharge() {// asking user for medication charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your medication charge");
double medicationCharge;
medicationCharge = sc.nextDouble();
return medicationCharge;
}
public static double labCharge() {//asking user for lab charge
Scanner sc = new Scanner (System.in);
System.out.println("What is your lab charge");
double labCharge;
labCharge = sc.nextDouble();
return labCharge;
}
public static double total (double medicineCharge, double labCharge, double overnightCharge) {
double totalCost;
if (overnightCharge == 0) {
totalCost = (overnightCharge + medicineCharge + labCharge); //Calculating all three charges
}
else {
totalCost = (medicineCharge + labCharge);
}
return totalCost;
}
}
You have changeŠ² the total method to
public static double total () {
return overnightCharge() + medicineCharge() + labCharge();
}
Also change main method to
public static void main(String[] args) {
System.out.println("Your total charge is: " + total());
}
First of all, you've defined three parameters for method "total," but you are specifying only one argument in your main method:
total(totalCost)
to minimize the number of things that you need to change in your code, I would simply change the total() method to:
public static double total() {
double totalCost = overnightCharge();
totalCost += medicationCharge();
totalCost += labCharge();
return totalCost;
}
and in your main method:
public static void main(String[] args) {
System.out.println("Your total charge is: " + total();
}
You are passing the wrong inputs to total, change your main to
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(medicationCharge(), labCharge(), overnightCharge()));
}
Also, in your total method, you don't need the if condition, so you can simplify it to:
public static double total(double medicineCharge, double labCharge, double overnightCharge) {
return (overnightCharge + medicineCharge + labCharge);
}
"Explanation why your code didn't work as desired: "
You have created a function total() which takes 3 arguments i.e (double medicineCharge, double labCharge, double overnightCharge)
public static double total (double medicineCharge, double labCharge, double overnightCharge) {
return totalCost;
}
But when you are calling this function in your main() you are only passing it a single argument that is total(totalCost).
public static void main(String[] args) {
System.out.println("Your total charge is: " + total(totalCost); // i want to print the "totalCost variable" returned by the "total" method.
}
You have also made a typo mistake "medicineCharge"
You can try something like this to achieve your desired output :
import java.util.Scanner;
public class Hospital {
static Scanner input;
private static double overnightCharge, medicationCharge, labCharge,
totalCost;
public static double takeInput() { // single function to take input
input = new Scanner(System.in);
return input.nextDouble();
}
public static double overnightCharge() {// asking user for overnight charge
System.out.println("What is your overnight charge");
overnightCharge = takeInput();
return overnightCharge;
}
public static double medicationCharge() {// asking user for medication
// charge
System.out.println("What is your medication charge");
medicationCharge = takeInput();
return medicationCharge;
}
public static double labCharge() {// asking user for lab charge
System.out.println("What is your lab charge");
labCharge = takeInput();
return labCharge;
}
public static double total() {
overnightCharge();
medicationCharge();
labCharge();
if (overnightCharge == 0) {
totalCost = (overnightCharge + medicationCharge + labCharge); // Calculating
// all
// three
// charges only when overnightCharge = 0
} else {
totalCost = (medicationCharge + labCharge);
}
return totalCost;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Total :" + total());
}
}
Note: I have also reduced the code for calling scanner again again.
I'm beginning to learn more about Java and I'm trying to code a Gratuity calculator that takes user Input, and shows how much a tip would be at %10 and %20 of the total. I'm getting a single "Cannot make a static reference to the non-static method" error that I can't resolve.
Gratuity class:
public class Gratuity{
//variables
private double total = 0;
private double grat1 = 0;
private double grat2 = 0;
public Gratuity(float value){
total = value;
}
start getters and setters
public double getTotal() {
return total;
}
//method to do the calculations
public void calcGrat(){
grat1 = total * .10;
grat2 = total * .20;
}
public double getGrat1(){
return grat1;
}
}
And the class with the main method:
import java.util.InputMismatchException;
import java.util.Scanner; //import package to use the scanner input function
//TestGrat main class contains method
public class TestGrat {
Scanner keyboard = new Scanner(System.in);
//method to prompt user for total, double is total
public void askForInput(){
try{
System.out.println("Enter the total amount of your bill");
total = keyboard.nextDouble();
}
catch(InputMismatchException e){
System.err.printf("Error, please try again. Program will now close");
System.exit(0);
}
}
public Scanner getKeyboard() {
return keyboard;
}
public void setKeyboard(Scanner keyboard) {
this.keyboard = keyboard;
}
//main method
public static void main(String[] args){
// asks for input in float form
float value = askForInput();
//Creating the gratCalc object and storing value as a float (total)
Gratuity gratCalc = new Gratuity(value);
// get the total value and set as float
float tot = (float)gratCalc.getTotal();
// converting the float value into string
System.out.println("You have entered: " + Float.toString(tot));
gratCalc.calcGrat(); //sets grat
// Displaying the options to user
System.out.println("Below are the tips for %10 as well as %20 ");
//getting the value and then displaying to user with toString
float getNum = (float) gratCalc.getGrat1();
float getNum1 = (float) gratCalc.getGrat2();
// using the value of getNum as float to put into toString
System.out.println( "For %10: " + Float.toString(getNum));
System.out.println(" For %20: " + Float.toString(getNum1));
}
}
Any help would be appreciated. Thanks!
askForInput() is inside your class TestGrat. However, in main() you are calling it directly, as if it was static. You probably meant:
TestGrat test = new TestGrat();
float value = test.askForInput();
askForInput() is also returning void, so you probably want to fix that too.
I need some help with a program for my programming class. It's a recursive program that takes a subtotal and a gratuity rate given by the user that outputs the full total and the gratuity cost. This is what I've got so far, and for some reason it just doesn't work:
import java.io.*;
import java.until.Scanner;
public class gratuity {
private double total;
private double subTotal;
private double gratRate;
private double newSubTotal;
private double newGratRate;
public static void main(String[] args) {
System.out.print("Enter the subtotal: ");
System.out.print("Enter the gratuity rate: ");
Scanner scan = new Scanner(System.in);
Scanner myScan = new Scanner(System.in);
double subtotal = scan.nextDouble();
double gratRate = myScan.nextDouble();
System.out.println("The Gratuity is: " + newSubtotal);
System.out.println("The Total is: " + Total);
}
public static double computeGratRate() {
double newGratRate = (gratRate/100);
return newGratRAte;
}
public static double computeNewSub() {
double newSubTotal - (subTotal * newGratRate);
return newSubTotal;
}
public static double computeTotal() {
double total = (newSubTotal + newGratRate);
return total;
}
}
If anyone would help me figure out how to fix it, I would be very grateful! Thank you!
A few things.
You are creating new variables called "subtotal" and "gratRate" in Main. These values override the member variables of the class.
Your problem won't compile anyway, because...
All your methods are static, which is OK, but these static methods are accessing non-static variables. Make all your member variables of this class static. (Or make everything outside of Main not static and then have "Main" be a stub to just create an instance of the gratuity class.
You need to import java.util.Scanner, not java.until.Scanner.
This line is a compiler error:
double newSubTotal - (subTotal * newGratRate);
I think you mean:
double newSubTotal = (subTotal * newGratRate);
That should be enough hints for now.... keep trying.
Did you mean:
import java.util.Scanner;
public class Gratuity {
private double subTotal;
private double gratRate;
public static void main(String[] args) {
Gratuity gratuity = new Gratuity();
System.out.print("Enter the subtotal: ");
Scanner scan = new Scanner(System.in);
gratuity.setSubTotal(scan.nextDouble());
System.out.print("Enter the gratuity rate: ");
Scanner myScan = new Scanner(System.in);
gratuity.setGratRate(myScan.nextDouble());
System.out.println("The new GratRate is: " + gratuity.getNewGratRate());
System.out.println("The New Sub is: " + gratuity.getNewSub());
System.out.println("The Total is: " + gratuity.getTotal());
}
public double getNewGratRate() {
return gratRate/100;
}
public double getNewSub() {
return getNewGratRate() * subTotal;
}
public double getTotal() {
return getNewSub() + getNewGratRate();
}
public double getSubTotal() {
return subTotal;
}
public void setSubTotal(double subTotal) {
this.subTotal = subTotal;
}
public double getGratRate() {
return gratRate;
}
public void setGratRate(double gratRate) {
this.gratRate = gratRate;
}
}
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));
}
I've messed around with this for an hour now and can't get it to work. I've also looked this question up but the wording used in answers I've found haven't helped me at all.
Any help would be much appreciated.
Also, the invocation in question is at the very end of the program, inside main.
import java.util.Scanner;
public class Area {
Scanner input = new Scanner (System.in);
/**
* #param args the command line arguments
*/
public static void areaTriangle (double height, double length){
System.out.println((height * length) * .5);
}
public static void areaRectangle (double height, double length,
double width){
System.out.println(height * length * width);
}
public static void areaCircle (double radius){
System.out.println(Math.PI * (radius * radius));
}
public void calcArea (){
double i;
System.out.println("Which shape's area would you like to calculate?: \n"
+ "Enter '1' for Triangle \n"
+ "Enter '2' for Rectangle \n"
+ "Enter '3' for Circle \n"
+ "Enter '0' to quit the program");
i = input.nextDouble();
if (i == 1)
{
System.out.print("Enter the height of your triangle: ");
double height = input.nextDouble();
System.out.print("Enter the height of your length: ");
double length = input.nextDouble();
areaTriangle(height, length);
}
else if ( i == 2)
{
System.out.print("Enter the height of your rectangle: ");
double height = input.nextDouble();
System.out.print("Enter the length of your rectangle: ");
double length = input.nextDouble();
System.out.print("Enter the width of your rectangle: ");
double width = input.nextDouble();
areaRectangle(height, length, width);
}
else if ( i == 3)
{
System.out.print("Enter the radius of your circle");
double radius = input.nextDouble();
areaCircle(radius);
}
else if ( i == 0)
return;
else
System.out.println("Please input a number from 0 - 3");
}
public static void main(String[] args) {
calcArea();
}
}
put static in calcArea
public static void calcArea ()
or you can do this in your main
public static void main(String[] args) {
YourClassName variable= new YourClassName();
variable.calcArea();
}
just change the "YourClassName" to the name of your class and also you can change the variable object