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);
}
}
Related
So currently, I'm struggling to make one particular program in eclipse for an assignment, while I am able to make most of the program, I seem to struggle with the no argument part of the program as well as bringing the pieces of the first class into the second for a brief moment. Here is my code for the first class
// Preparation of the input
import java.util.Scanner;
public class primarySetUp {
public static void main(String[] args) {
// Variable Declaration
double userBagNumber;
double userBagWeight;
// Create Scanner
Scanner input = new Scanner(System.in);
java.util.Date date = new java.util.Date();
// Opening Statement
System.out.println("Welcome to the Coffee Sales Simulation!");
// Get User Input
System.out.println("How heavy do you want the bags to be?");
userBagWeight = input.nextDouble();
System.out.println("How many bags do you want?");
userBagNumber = input.nextDouble();
// Get output
// Date
System.out.println("Todays date: ");
System.out.printf("%tB %<te, %<tY", date);
System.out.println(""); // spacer
// Original Inputs
System.out.printf("\nNumber of Bags: %3.0f", userBagNumber);
System.out.printf("\nWeight of Each Bag: %3.2f", userBagWeight);
System.out.print(" lbs");
// Calling of the Class
secondarySetUp mysecondarySetUp = new secondarySetUp(userBagWeight, userBagNumber);
// End Program
System.out.println("\nThank you for shopping with us!");
}
}
and here is my code for the second class, which is full of errors in this case.
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
public secondarySetUp(double userBagWeight, double userBagNumber) {
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// No argument pricing
public Sale() {
singleBagger = 1;
pounderBagger = 1;
}
// First constructor receiving No argument pricing
public Sale(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
If you have any sort of fixes I could apply, please let me know; I am planning on adding the print statements for the rest of the arguments as well, but I'd like to get Sale() fixed up first.
I see a problem in getSale() where you are trying to use userBagWeight, but that variable doesn't exist outside the constructor parameters, which could create a lot of problems since other methods are calling on it. The constructor taking
double userBagWeight, double userBagNumber, yet it's not assigning them to any fields or doing anything with them.
I missed the part where you are treating Sale() as a constructor, but those are no constructors. The constructor is named after your class name.
public secondarySetUp(double userBagWeight, double userBagNumber)
change Sale() to secondarySetUp and you will be fine.
here how your class should be like :
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
double userBagWeight, userBagNumber;
public secondarySetUp(double userBagWeight, double userBagNumber) {
this.userBagWeight = userBagWeight;
this.userBagNumber = userBagNumber;
singleBagger = 1;
pounderBagger = 1;
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// First constructor receiving No argument pricing
public secondarySetUp(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
this is a keyword to tell the program that we want to use the field "instance variable", if we have a method with parameter that have same name as a field name, then to tell them apart we tell the program this.fieldName to know which one we talking about.
i'm still pretty new with Java and am trying to write a program that will show me how much my money is actually getting me whenever i make an ingame purchase.
I'm struggling with getting the value from the method convertYourself() into my main method so that i can combine them.
I think i would most likely need make it a double instead of a void and return it but what would i pass as the parameter?
Thank you!
public class TestCode {
Scanner in = new Scanner(System.in);
public static double gemValue = 0.01;
public static double goldValue = 0.000004;
public static void main(String[] args) {
TestCode test = new TestCode();
test.convertYourself(gemValue);
test.convertYourself(goldValue);
// double sum = how do i get the value of the convertYourself method so i can use it here?
System.out.println("The total value of this bundle is :" + sum);
}
public void convertYourself(double x) {
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
System.out.println("The true value of this is: " + convert);
}
}
You would need to have the method to return a value. That can be done like this:
public double convertYourself(double x) {
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
return convert;
}
//To call it:
double valueReturned = convertYourself(gemValue);
So, you would have to change the method return value from void to double, and use the return keyword to return the value you want.
You can use a return type instead of void for a method.
The return value must then be returned via return {value}.
// return type
// \/
public double convertYourself (double x) {
double convert = /* convert */;
return convert;
}
After that you can store the output in a variable:
double result = convertYourself (/* x */);
To be more specific with the coding part:
public class TestCode {
Scanner in = new Scanner(System.in);
public static double gemValue = 0.01;
public static double goldValue = 0.000004;
public static void main(String[] args) {
// TestCode test = new TestCode(); ... you do not need this as the both methods are inside the same class. Make the convertYourself method as *static*.
double gemValueConverted = convertYourself(gemValue); // call it without the object
double goldValueConverted = convertYourself(goldValue);
double sum = gemValueConverted + goldValueConverted;
System.out.println("The total value of this bundle is :" + sum);
}
public static double convertYourself(double x) { // made the method static and added return type as double
System.out.println("How many are you buying?");
double currency = in.nextDouble();
double convert = currency * x;
System.out.println("The true value of this is: " + convert);
return convert;
}
}
I'm working on a program that takes the input of two numbers and then does some different calculations. I have my TwoNumbers class with several different methods to calculate sum, distance, average, etc.
Should I put the scanner in this class, or should I put it in the Main method?
I know this is really basic but I've only been learning java for a couple weeks and I'm having a hard time finding how this should be done/how to get the input to correlate to my instance variables and firstNumber and secondNumber
public class TwoNumbers{
private double firstNumber;
private double secondNumber;
public double getSum()
{
double sum = firstNumber + secondNumber;
return sum;
}
public double getDifference()
{
double difference = firstNumber - secondNumber;
return difference;
}
public double getProduct()
{
double product = firstNumber - secondNumber;
return product;
}
public double getAverage()
{
double average = (firstNumber + secondNumber) / 2;
return average;
}
public double getDistance()
{
double distance = Math.abs(firstNumber - secondNumber);
return distance;
}
public double getMax()
{
double maximum = Math.max(firstNumber, secondNumber);
return maximum;
}
public double getMin()
{
double minimum = Math.min(firstNumber, secondNumber);
return minimum;
}
}
Each class should follow the single responsibility principle. Your TwoNumbers class should only work with the double numbers and perform operations on them, nothing more. Providing the double numbers for this class should be in the client, and also the ability to provide the numbers, which means that the client may define the Scanner or another way to provide the data.
The class you have displayed, the TwoNumbers class, should have no user input in it as it should encapsulate the concept of two numbers and two numbers only. It should be written in such a way that it can be used with a Scanner program or with a GUI program without having to change it. Thus the UI should be in main or in another class.
You would probably want to make a constructor for the class, and within the constructor pass the variables you want. This would mean that you get your input from somewhere else, IE the main method or some other means.
public TwoNumbers(double num1, double num2){
firstNumber = num1;
secondNumber = num2;
}
For example:
public double getSum(firstnumber, secondnumber) // <-- you need pass in the value
{
double sum = firstNumber + secondNumber;
return sum;
}
/*
* somewhere in the main or another method you can delare the first number / 2nd number
* for example:
*/
public void static main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter first number");
firstnumber = input.nextInt();
System.out.println("enter first number");
secondnumber = input.nextInt();
}
After that all you need to do is just calling the method you want to pass the number to.
You need to have a constructor in TwoNumbers:
public class TwoNumbers {
private double firstNumber;
private double secondNumber;
public TwoNumbers(double firstNumber, double secondNumber){
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
}
}
Then in some other Class, you can have your scanner:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter firstNumber");
double firstNumber = scanner.nextDouble();
System.out.println("Enter secondNumber");
double secondNumber = scanner.nextDouble();
TwoNumbers obj = new TwoNumbers(firstNumber, secondNumber);
//Call methods from TwoNumbers
}
Really the code would work if you put the scanner in the main class or in the TwoNumbers class. The best practice way of doing this would be to place your scanner and any other input/output code in you main class, and the processing/calculation code in another class. Which one you choose will be based on your application, but most of the time you will have the scanner in the main class. So...
public class Driver {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String s;
while((s = in.nextLine()) != "stop"){
TwoNumbers.sum(Double.parseDouble(s.split(" ")[0]), Double.parseDouble(s.split(" ")[1]));
}
in.close();
}
}
public class TwoNumbers{
public static double sum(double a, double b){
return a+b;
}
}
}
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
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
}