Calling methods with parameters in Java - java

So I have to make a program in class and i'm having some trouble.
I have to call the examAverage method, which has parameters and i'm not sure how to. Also, in the user prompts method, I have to make a loop in main that call user prompts method and ask the user to input their exam score 3 times to get the average. I hope I explained it well. Im not very good at programming.
package project5;
import java.util.*;
public class Project5 {
static final int NUM_EXAMS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
//declare variable
double Average;
double examScore1 = 0;
double examScore2 = 0;
double examScore3 = 0;
double Average = examAverage(examScore1, examScore2, examScore3) / NUM_EXAMS;
printWelcome();
userPrompts();
display();
}
static void printWelcome() {
System.out.println("Welcome to the Exam Average Calculator");
}
public static void userPrompts() {
System.out.println("Please enter your 1st exam score.");
double examScore1;
examScore1 = console.nextDouble();
System.out.println("Please enter your 2nd exam score.");
double examScore2;
examScore2 = console.nextDouble();
System.out.println("Please enter your 3rd exam score.");
double examScore3;
examScore3 = console.nextDouble();
}
public static void display() {
double examAverage = 0;
}
public static double examAverage(double examScore1, double examScore2, double examScore3, double sum, double NUM_EXAMS) {
double Average;
sum = examScore1 + examScore2 + examScore3;
Average = (double) sum / NUM_EXAMS;
return Average;
}
public static void displayAverage(double Average) {
Object[] examAverage = null;
System.out.println("Your exam average is %.2f%", examAverage);
}
public static double examAverage(double examScore1, double examScore2, double examScore3) {
double Average;
{
return double Average

I don't want to do your homework for you but you call a method with paramaters severals times in your code. For example inside your main:
examAverage(examScore1, examScore2, examScore3)
you call the examAverage method passing in 3 variables. Your three variables are all set to 0, so that makes no sense. you probably should call your userPrompts before you call your examAverageMethod to initialize your examscores.
your program looks like it's almost done, think about the order of how you want to do it. good luck

So your exam average function is all messed up, what you want is it to take number of exams and the individual values and return the average.
So you make the function like this because you don't need to have sum as a parameter.
public static double examAverage(double examScore1, double examScore2, double examScore3, double NUM_EXAMS) {
double Average;
double sum = examScore1 + examScore2 + examScore3;
Average = sum / NUM_EXAMS;
return Average;
}
So when you call this function, you need to give it 4 values
so call it like this
double Average = examAverage(examScore1, examScore2, examScore3, 3);
That should solve your issue with the function. Let me know if I didn't explain it clearly enough or if you want me to elaborate.
You also have an issue on what order you call your code.
First, you want to welcome the user, then you want to ask them for their values, then you want to use those values to calculate the average and then you want to print that average so do this instead.
//declare variable
double Average;
double examScore1 = 0;
double examScore2 = 0;
double examScore3 = 0;
//Welcomes user, then prompts for exam values, calculates average using those values, and finally displays the average
printWelcome();
userPrompts();
double Average = examAverage(examScore1, examScore2, examScore3, 3);
System.out.println("your average is" + Average)
Also, delete your Display() and DisplayAverage() functions, they are useless.

On way would be to call your variables static by defining at class level like:
private static double examScore1 = 0;
private static double examScore2 = 0;
private static double examScore3 = 0;
Other best way would be to wrap all these variables in a class (or better create a list/array) and pass that call in userPrompts method and populate it and then using same object you calculate average.
Regarding looping, here's how you could do it:
create a counter and initialize it with 0.
while count <= 3
do
ask input from user
calculate average
display the average
done

Related

Java methods interacting with each other

I am currently learning Java and following some online tutorials. One of the assignments is to compute the body age of a person by getting their various scores, getting the average of these scores and then applying a formula to it to get the total. I can do it with one big class, but the assignment then asks to go further and split everything into different classes. My program currently looks like this:
import java.util.Scanner;
public class fit2 {
public static void main(String[] args) {
int average, bodyAge;
average = average2();
System.out.println(average);
bodyAge = fitAge();
System.out.println(bodyAge);
}
public static int fs() {
int fs;
System.out.println("Enter first number: ");
Scanner bucky = new Scanner(System.in);
fs = bucky.nextInt();
return fs;
}
public static int ss() {
int ss;
System.out.println("Enter second number: ");
Scanner bucky = new Scanner(System.in);
ss = bucky.nextInt();
return ss;
}
public static int average2() {
int first, second, average;
first = fs();
second = ss();
average = (first + second) / 2;
return average;
}
public static int fitAge() {
int fitAge, average;
average = average2();
fitAge = average * 8 / 5 + 10;
return fitAge;
}
}
My idea was to have different methods for each part of the program - two methods to get the users scores and then pass these into a averageing method, which would then pass it into a final method which would apply the formula, then passing it back it into the Main class, which would print that age out as well as the Average age.
I read somewhere that you shouldnt get user input in classes but get it in main and pass it into the average class using parameters -- can anyone advise on this?
Thanks.
Try something like this (as suggested by my comment on the question):
import java.util.Scanner;
public class fit2 {
public static void main(String[] args) {
System.out.println("Enter first number: ");
Scanner bucky = new Scanner(System.in);
int fs = bucky.nextInt();
System.out.println("Enter second number: ");
bucky = new Scanner(System.in);
int ss = bucky.nextInt();
int average = average2(fs, ss);
int bodyAge = fitAge(average);
System.out.println(average);
System.out.println(bodyAge);
}
public static int average2(int first, int second) {
int average;
average = (first + second) / 2;
return average;
}
public static int fitAge(int average) {
int fitAge;
fitAge = average * 8 / 5 + 10;
return fitAge;
}
}
I believe I understand your question - you are unsure of where to place user input in your program.
In a small program like this, it may be wise to place user input in the main() method, solely because you gather user input, delegate input to methods that perform computation on the data that is "under the hood" of the program, and then return the value back to the user.
In your specific instance, this seems like a wise decision, as your program is small and a standard console-based application. This may not always be the case in the future, depending on the program you are writing.
Realistically, it doesn't matter all too much if it runs as intended, but for simplicity sake (remember KISS) putting user input in your main() method is probably a good idea.

How do I use the return value from a method in another method different from the calling method?

I'm kinda new to to java and stumbled on a problem that needs me to do currency conversion declaring different methods for:
getting amount, getting conversion rate, doing the actual conversion and printing the outcome of the conversion
import java.util.*;
public class Conver {
public static void main(String[] args){
amountToConvert();
exchangeRate();
convert();
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(){
int x = amount*rate;
return x;
}
public void printResult(){
System.out.println(x);
}
}
Learn to use parameters in the methods. Change the convert() method so that it looks like this:
public static double convert(double amount, double rate){
int x = amount*rate;
return x;
}
In the method above, double amount and double rate are the parameters. Use variables to help pass in parameters to convert() in the main method:
public static void main(String[] args){
double amount1 = amountToConvert();
double rate1 = exchangeRate();
double result = convert(amount1, rate1);
printResult(result);
}
Hope this helps!
Pass returned values to the method convert:
import java.util.*;
public class Conver {
public static void main(String[] args){
double amount = amountToConvert();
double rate = exchangeRate();
double result = convert(amount, rate);
printResult(result);
}
public static double amountToConvert() {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount you wish to convert...");
double amount = input.nextDouble();
return amount;
}
public static double exchangeRate(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the currency you wish to convert from... ");
String initialCurrency = input.next();
System.out.println("Enter the currency you wish to convert from... ");
String finalCurrency = input.next();
System.out.println("How many " + initialCurrency + " makes one " + finalCurrency + "?");
double rate = input.nextDouble();
return rate;
}
public static double convert(double amount, double rate){
double x = amount * rate;
return x;
}
public void printResult(double x){
System.out.println(x);
}
}
Also, don't use double for money!
First off, you need to change the "receiving method" so that it takes an argument. A method like:
public static double convert() {}
that needs to take in a value for amount and rate, needs to have those added to the method signature:
public static double convert (double amount, double rate) {}
Putting the two comma separated values inside of the parens means that this method takes two values, doubles, as arguments. This makes those values available to use inside of that method.
Now that you have a method that can take the required arguments, you need to actually use that method in your code. When calling this method, you start out the same as with others:
convert(
but then you need to add in the arguments you are using:
double amount = amountToConvert();
double rate = exchangeRate();
convert(rate, amount);
If you want to avoid creating those two additional variables in main(), you can actually call those methods inside of your new method:
convert(amountToConvert(), exchangeRate());

Java Averaging Program

Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
 A method that accepts two integer parameters and returns their average.
 A method that accepts three integer parameters and returns their average.
 A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
I am totally new to Java and programming, this has me completely lost! Here's what I've tried.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
}
public double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
public double average (int num1, int num2, int num3)
{
return (num1 + num2 + num3) / 3.0;
}
}
The program doesn't go past getting the values from the user. Please help!
You have to actually call your methods.
Just place
Average avg = new Average();
System.out.println("The average is: " + avg.average(numb1, numb2));
at the end of your main method.
Alternatively you can make the methods static:
public static double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
More info on constructors and static.
It looks like your not actually printing out the results. Try the following.
System.out.print(average(numb1, numb2));
Let's detail what you did there.
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
}
Then your two next methods compute for two or three given integers their average.
The main method is the first method called during your program execution. The jvm will execute everything inside. So it will declare the three doubles, read two values from keyboard and then end.
If you want to compute the average of numb1 & numb2 using your method, you have to create an object Average and call your average method like this
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
//Declare the average value
double average;
//Create an average instance of the class average
Average averageObject = new Average();
//Call your average method
average = averageObject.average(numb1,numb2);
//Print the result
System.out.println("Average is : " + average);
}
Everything in Java is object (read about Object Oriented Programming).
Writing your class "Average" defines how your object is structured. It has attributes (characteristics) and methods (actions). Your Average object has no attributes. However it has two methods (average with two and three numbers) acting on integers.
However your class is just the skeleton of your object. You need to create an object from this skeleton using the keyword new as :
Average averageObject = new Average();
Sincerely
public class Marks {
int roll_no;
int subject1;
int subject2;
int subject3;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public void getDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of subject1");
this.subject1 = sc.nextInt();
System.out.println("Enter the marks of subject2");
this.subject2 = sc.nextInt();
System.out.println("Enter the marks of subject3");
this.subject3 = sc.nextInt();
System.out.println("Enter the roll number");
this.roll_no = sc.nextInt();
}
public int getAverage(){
int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
return avg;
}
public void printAverage(){
System.out.println("The average is : " + getAverage());
}
public void printRollNum(){
System.out.println("The roll number of the student is: " + getRoll_no());
}
public static void main(String[] args){
Marks[] e1 = new Marks[8];
for(int i=0; i<2; i++) {
System.out.println("Enter the data of student with id:");
e1[i] = new Marks();
e1[i].getDetails();
e1[i].printAverage();
}
System.out.println("Roll number details");
for(int i=0; i<2; i++){
e1[i].printRollNum();
}
}
}
If you'd like your program to find the average you need to include a call to that method in your main method.
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println("The average of " + numb1 + " and " + numb2 + " is " + average(numb1,numb2);
}
you need to call the methods that you have written after you accept the input.
...
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println(average (int numb1 , int numb2 ))
...
You probably want to provide a menu of options for the user to select to determine which method to call
System.out.println("Select one option");
System.out.println("1. Enter two numbers you'd like to be averaged.");
System.out.println("2. Enter the 3 numbers you want averaged.");
System.out.println("3. Enter the number Range you want averaged.");
and based on that answer you can determine which method to call
After the access specifier (public) and before the return type (double) place the Java keyword static. You shouldn't worry about what this means right now.
You have to use bitwise operators.
average of int a and b can be calculated as
avg= (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1);
The main method will only execute what it is asked to. If you want the average methods to be executed, you will have to create an object, pass the required variable and call the methods from the main method. Write the following lines in the main method after accepting the input.
Average avrg = new Average();
System.out.println("The average is: " + avrg.average(numb1, numb2, numb3));
Write only numb1 and numb2 if you want to average only two numbers.

Calling results from methods outside main into variables in the main method

My homework is to calculate taxes and surcharges for a jewelry store that is replenishing its stock, and I have run into a slight snag. I am using a method called calcExtraTax three times to calculate the labor rate and state and federal taxes. I then need to take the results of each instance of that method and pass the value into the appropriate variable in my main method. This is what my code looks like right now (evidently not complete):
import java.text.DecimalFormat;
import java.util.Scanner;
import javax.swing.JOptionPane;
public static void main(String[] args)
{
double stateRate = 0.1;
double luxuryRate = 0.2;
double laborRate = 0.05;
double extraCharge;
int numOrdered;
double diamondCost;
double settingCost;
double baseCost;
double totalCost;
double laborCost;
double stateTax;
double luxuryTax;
double finalAmountDue;
Scanner keyInput = new Scanner(System.in);
System.out.println("What is the cost of the diamond?");
diamondCost = keyInput.nextDouble();
System.out.println("What is the cost of the setting?");
settingCost = keyInput.nextDouble();
System.out.println("How many rings are you ordering?");
numOrdered = keyInput.nextInt();
baseCost = diamondCost + settingCost;
calcExtraCost(baseCost, laborRate);
laborCost = extraCharge;
calcExtraCost(baseCost, stateRate);
stateTax = extraCharge;
calcExtraCost(baseCost, luxuryRate);
luxuryTax = extraCharge;
totalCost = baseCost + laborCost + stateTax + luxuryTax;
finalAmountDue = numOrdered*totalCost;
JOptionPane.showMessageDialog(null, "The final amount due is = " + finalAmountDue);
}
public static void calcExtraCost(double diamond, double rate)
{
double extraCharge = diamond*rate;
???????????
}
what i'm trying to figure out is what else i need to put in my secondary method in order to be able to pass the result into a different tax cost variable each time depending on the rate variable used in the formula.
You don't need to do anything special with your calcExtraCost apart from changing the return type to double and returning the calculated value. For example
public static double calcExtraCost(double diamond, double rate)
{
double extraCharge = diamond*rate;
double tax = //some calculations
return tax
}
So this method would return the calculated value.
In your main method you need to store that value to the appropriate double that you want. For example if you want to calculate the luxuryTax, then you do something like:
luxuryTax = calcExtraCost(baseCost, luxuryRate);
Also some advice, instead of making your method static, make it a non-static method, and create an object of the class where your method is defined, and call the method on that object.
For example if the class where you defined your method is called Tax, then you create an object of Tax:
Tax tax = new Tax();
and call calcExtraCost on that object:
tax.calcExtraCost();
This way you remove the static part of the method. So your method signature becomes like this:
public double calcExtraCost(double diamond, double rate)
You can return the value of diamond*rate from your helper method by changing its signature from void to double and adding a return statement:
public static double calcExtraCost(double diamond, double rate)
{
return diamond * rate;
}
Now you can assign the result of a call to the variable in your main method:
laborCost = calcExtraCost(baseCost, laborRate);

Computing the average of an array

This is a code to take user imputed grades, find their average, the deviation, and display this information in a table style. My program takes user input and displays the information well, but it won't compute the average and the deviation properly. When run, it says the average is 0. I'm doing it the same why my teacher taught us, but I can't find my error.
import java.util.Scanner;
public class ClassScores{
public static void main(String[] args){
String[] names = {"Bashful","Doc","Dopey","Grumpy","Happy","Sleepy","Sneezy"};
double[] grades = new double[7];
double mean=0;
double[] difference = new double[7];
getScores(grades);
average(grades, mean);
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
}
public static double[] getScores(double[] grades)
{
Scanner kb= new Scanner(System.in);
System.out.println("Enter grades for students in alphabetical order.");
for (int i=0;i<grades.length; i++)
{
grades[i]=kb.nextDouble();
}
return grades;
}
public static double average(double[] grades, double mean)
{
double total = 0;
for (double i : grades)
{
total += i;
}
if (grades.length>0)
{
mean = total/grades.length;
}
return mean;
}
public static double[] deviation(double[] grades, double mean, double[] difference)
{
for (int i=0; i<grades.length; i++)
{
difference[i]=grades[i]-mean;
}
return difference;
}
public static void displayResults(String[] names, double[] grades, double[] difference, double mean)
{
System.out.println("The average score is" +mean);
System.out.println("Student Name Grade Mean Deviation");
for (int i=0; i<names.length; i++)
{
System.out.printf(names[i]);
System.out.printf("%20f", grades[i]);
System.out.printf("%20f", difference[i]);
System.out.println();
}
}
}
Here is the edited code for anyone who's curious.
import java.util.Scanner;
public class ClassScores{
public static void main(String[] args){
String[] names = {"Bashful","Doc","Dopey","Grumpy","Happy","Sleepy","Sneezy"};
double[] grades = new double[7];
double mean=0;
double[] difference = new double[7];
getScores(grades);
mean = average(grades);
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
}
public static double[] getScores(double[] grades)
{
Scanner kb= new Scanner(System.in);
System.out.println("Enter grades for students in alphabetical order.");
for (int i=0;i<grades.length; i++)
{
grades[i]=kb.nextDouble();
}
return grades;
}
public static double average(double[] grades)
{
double total = 0;
for (double i : grades)
{
total += i;
}
return total/(grades.length);
}
public static double[] deviation(double[] grades, double mean, double[] difference)
{
for (int i=0; i<grades.length; i++)
{
difference[i]=grades[i]-mean;
}
return difference;
}
public static void displayResults(String[] names, double[] grades, double[] difference, double mean)
{
System.out.println("The average score is" +mean);
System.out.println("Student Name Grade Mean Deviation");
for (int i=0; i<names.length; i++)
{
System.out.printf(names[i]);
System.out.printf("%20f", grades[i]);
System.out.printf("%20f", difference[i]);
System.out.println();
}
}
}
You never actually use the return result of the average method. You probably meant to pass that to displayResults, or assign it to mean in the main() method.
First, your average method should look more like this:
public static double average(double[] grades)
{
// Error check up front.
if (grades.length == 0) {
throw new InvalidArgumentException("length is 0");
}
// These next lines are good.
double total = 0;
for (double i : grades)
{
total += i;
}
// Then you can just divide and return.
return total / (grades.length);
}
There's no reason to pass a mean parameter to the average method. That'd be like passing a Dog to a createDog method.
But more importantly, while you call average, you don't store the result anywhere. You're just ignoring it.
If you're coming from a background with pointers, remember that Java passes primitives by value - changing mean, a double, inside the method will have no effect on the value outside the method. Instead, have
double mean = average(grades);
So the underlying reason why mean is zero is because you set it to zero, and never change it:
double mean = 0;
You are returning your mean value, but you aren't assigning the result of the method call to average to anything. What you want is to assign the result of the method to the variable:
mean = average(grades);
And in your average method, you don't need to take mean as a parameter, just declare it locally and return it.
average(grades, mean); sends copies of the variables to the average() method. The mean variable inside of average() has nothing to do with the mean variable inside of main() despite the same name. To fix the problem, you need to do something like
mean = average(grades, mean);
I also suggest that you remove the mean parameter and declare a local variable inside of average(). Then you can just do
mean = average(grades);
You have this method declared to return a value:
public static double average(double[] grades, double mean)
but in your main method, you do not use the result returned. You are then printing out the
value of the other "mean" variable which is global to that function, and is assigned a value of 0.
double mean=0;
double[] difference = new double[7];
getScores(grades);
**average(grades, mean);**
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
I think you want :
getScores(grades);
**mean = average(grades, mean);**
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);

Categories