While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java
Related
I am trying to make a simple program that takes the average of three number, but I get an error saying that says
"constructor average in class average cannot be applied to given types;
required: no arguments
found: int,int,int "
Here is my code:
public class ave {
public static void main(String args[]) {
average object = new average(3,4,6);
}
}
and here is my constructor code
public class average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
The constructor's name should be same as the class name and feature no return type.
Try the following:
public class ave {
public static void main(String args[]) {
Average object = new Average(3,4,6);
}
}
public class Average {
public Average(double first, double second, double third){
double ave = (first + second + third)/3;
System.out.println(ave);
}
}
and if you don't want to change the code of Class Average, then just call the method from that class as following:
public class ave {
public static void main(String args[]) {
Average object = new Average();
double Avg = object.takeaverage(3,4,6);
}
}
public class Average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
The constructor must have the same name as the class.
You have to create:
public average(double a, double b, double c)
Actually the only constructor existing in the class is the constructor without arguments, that is created automatically.
You have not defined a constructor method that receives these arguments (3, 4, 6).
You have to create a constructor method like this:
public class average {
public double result
public average(int a, int b, int c){
this.result=this.takeaverage(double(a),double(b),double(c))
}
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave; }
}
If you only want to take the average of 3 numbers, you can do it without creating an average object. I have shown it below:
import java.util.*;
public class Ave {
public static void main(String[] args){
double number1, number2, number3;
Scanner console = new Scanner(System.in);
System.out.println("Enter number 1:");
number1 = console.nextDouble();
System.out.println("Enter number 2:");
number2 = console.nextDouble();
System.out.println("Enter number 3:");
number3 = console.nextDouble();
double average = (number1 + number2 + number3)/3;
System.out.println("The average is: " + average);
}
}
The above program asks the user for 3 numbers and prints out their average. Note that it is still a bit redundant. You can also modify it to ask for average of any numbers, like shown below:
import java.util.*;
public class Ave {
public static void main(String[] args){
int howMany;
double sum = 0.0;
double number, average;
Scanner console = new Scanner(System.in);
System.out.println("How many numbers do you want to take average of:");
howMany = console.nextInt();
int count = 1;
while(count <= howMany){
System.out.println("Enter number " + count);
number = console.nextDouble();
sum += number;
count++;
}
average = sum/howMany;
System.out.println("The average is: " + average);
}
}
You can modify the programs to take the average of 3 numbers without asking the user too, where the doubles number1, number2, and number3 will be given numbers (hard-coded, which is not a good practice in general).
You have created the "takeaverage" method but haven't invoked it. And maybe you should use a setter or pass the three numbers using the constructor and initialize and then only call the "takeaverage" method for a double value and get the average assigned to that double variable.
You need to use the default constructor and create the object from "average" class. Below is a very simple solution :
public class average {
public double takeaverage(double first, double second, double third) {
double ave = (first + second + third)/3;
System.out.println(ave);
return ave;
}
}
//main class
public class ave{
public static void main(String []args){
average object = new average();
object.takeaverage(3,4,6);
}
}
EDIT: HERE IS A SCREENSHOT OF THE OUTPUT
https://www.dropbox.com/s/93d09a627se3b1u/Screenshot%202015-09-16%2019.08.19.png?dl=0]
I was recently asked to make a program that can calculate and display...
1 / (1!) + 1 / (2!) + . . . 1 / (n!)
using the Scanner utility. I seem to be having a lot of trouble with this. the program itself works, but it somehow gives the same answer no matter what number I input. Here's what I have so far (And yes, it is purposely incomplete, I'm stumped).
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math.E);
}
public static void Math(Double E)
{
Double product = 1.0;
int x = 0;
while (E > 0)
{
product = product * E;
E--;
}
Can anyone give me a way to finish/solve this problem? Thanks a ton.
~Andrew
EDIT: This code works fine for just finding the extreme. I will work on a way to add the preceding components of the equation to this, but It's a bit tricky for me.
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math(n));
}
public static Double Math(Double E)
{
Double product = 1.0;
while (E > 0)
{
product *= E;
E--;
}
return product;
}
}
You are confused with too much Math.
You've got your method Math with a parameter E and the Java Math class with a constant E. You're mixing them up.
Try
public static double factorial(double v)
{
double product = 1.0;
while (v > 0)
{
product *= v;
v--;
}
return product;
}
Your code:
System.out.println("e = " + Math.E);
Math.E is a constant - it will always print the euler number hence your output.
To call the the method correctly it should be
System.out.println("e = " + math(e)"
Input 1 - Output 1
Input 2 - Output 1.5
Input 3 - Output 1.66666667
import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . + 1/(n!)\nWhat is the value of n?");
double n = input.nextDouble();
double solution = doMath(n);
System.out.println("e = " + solution);
}
public static double doMath(double n) {
double ret = 0;
// the number of terms we add
for (int i = 1; i <= n; i++) {
ret += calcFaculty(i);
}
return ret;
}
// calculate every single term
public static double calcFaculty(double d){
double calc = 1;
for (int i = 1; i <= d ; i++) {
calc = calc* 1/i;
}
return calc;
}
}
Hi Andrew the program always return the same number
e = 2.718281828459045
Because the line System.out.println("e = " + Math.E); is not calling the method Math but calling to the class java.lang.Math. I dont know if is this what you find dubious.
import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}
I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}
Currently I am writing a program for an introductory Java class. I have two pieces to my puzzle. Hopefully this is a relatively simple to answer question.
Firstly, here is what I am trying to use as my main program:
import java.util.Scanner;
public class TheATMGame
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double newBalance = 0;
double monthlyInterest = 0;
int answer = 0;
int i=1;
while (i < 100) {
System.out.print ("Please enter your ID: ");
answer = input.nextInt();
System.out.println(" ");
if (answer >=0 && answer<10)
TheATMGame.runGame (answer);
else
System.out.println("Sorry, this ID is invalid.");
}
}
public static void runGame(int id) {
double amount = 0;
int continueOn = 0;
while (continueOn < 4) {
ATMGame myATM = new ATMGame();
Scanner input = new Scanner(System.in);
System.out.println ("---Main menu--- ");
System.out.println ("1: Check balance ");
System.out.println ("2: Withdraw ");
System.out.println ("3: Deposit ");
System.out.println ("4: exit ");
int answer = input.nextInt();
if (answer == 1)
System.out.println("your balance is: " + myATM.getBalance (id));
else if (answer == 2){
System.out.println("Enter an amount to withdraw: ");
amount = input.nextInt();
myATM.withdraw(amount, id);
}
else if (answer == 3)
{
System.out.println("Enter an amount to deposit: ");
amount = input.nextInt();
myATM.deposit(amount, id);
}
else if (answer == 4)
continueOn = 4;
else if (answer > 4)
System.out.println ("Please review the main menu. " +
"Your selection must be between 1-4.");
}
}
//ATM class (balance, annualInterestRate2, id2)
//ATM myATM = new ATM (20000, 4.5, 1122 );
//newBalance = myATM.withdraw(2500);
//newBalance = myATM.deposit(3000);
//monthlyInterest = myATM.getMonthlyInterestRate();
//System.out.println("Your current balance is: " + newBalance);
//System.out.println ("Your monthly interest rate is: " + monthlyInterest);
}
Now here are all of the classes I want to impliment into that program:
import java.util.Date;
public class ATMGame {
private double annualInterestRate = 0;
private double balance = 0;
private int id = 11;
private int[] ids = {0,1,2,3,4,5,6,7,8,9};
private int[] balances = {100,100,100,100,100,100,100,100,100,100};
public Date dateCreated;
public ATMGame() {
}
public ATMGame (double balance2, double annualInterestRate2, int id2) {
balance = balance2;
annualInterestRate = annualInterestRate2;
id = id2;
dateCreated.getTime();
}
public double getMonthlyInterestRate() {
double monthlyInterest = annualInterestRate/12;
return monthlyInterest;
}
public double withdraw(double amountWithdrawn, int id) { //This method withdraws money from the account
double newBalance = balances[id] - amountWithdrawn;
System.out.println("Your withdrawel has processed. New balance: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double deposit(double amountDeposited, int id) { //This method deposits money in the account
double newBalance = balances[id] + amountDeposited;
System.out.println("Your deposit has processed. New Balance is: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double getBalance(int id) {
double myBalance = balances[id];
balance = myBalance;
return myBalance ;
}
}
When I try to run the first program it says "No Main classes found."
As you can see I have written the line " public void Main() ..." to take care of this, but eveidently it does not work. What am I doing wrong?
Replacing "public void Main() {" with "public static void main(String[] args) {" still returns the error: "No Main classes found." :/
http://img21.imageshack.us/img21/9016/asdfsdfasdfg.jpg
I was able to fix it by changing Main.java to TheATMGame.java and then running from ATMGame.java.
You should use:
public static void main(String[] args)
Instead of Main because the JVM calls this method first. It is a convention.
You've just misdefined main. Should be:
public static void main(String[] args) {
....
}
You're going to run into some other problems with your code, though. From a quick glance...
Your main() is a function, as well as runGame() - one shouldn't be defined within the other.
You cannot name your two classes the same thing - call the main() class something different than ATMGame.
Not sure where you're going with ATM class (balance, annualInterestRate2, id2), but it's not valid Java.
Your method signature must be:
public static void main(String[] args) {
...
}
That's the convention you have to follow. Anything else won't work.
In your class ATMGame, replace the following:
public void Main() {
with:
public static void main(String[] args) {
Additionally, since this method has to be static, you'll need to change the following:
if (answer >=0 && answer<10)
runGame (answer);
else
with:
if (answer >=0 && answer<10)
ATMGame.runGame (answer);
else
Then finally, you need to change the method signature of rungame to also be static. Change it from:
public void runGame(int id) {
to:
public static void runGame(int id) {
The names of your public classes should match the file names. This is not the case in your screenshot. Also make sure that everything compiles correctly and then retry (using a public static void main(String[] args) { ... } method).