How to pass variables from one method to another? - java

Trying to write a grade calculator program and am running into problems passing return variables from one method to another. I'm new to coding so I'm sure this isn't very pretty, but was hoping to get some help.
I have a method to calculate the Homework score, a method to calculate the midterm score, and a method to calculate the final score. I'm trying to call the return variables in the last method to calculate overall grade. The error is when calling the courseScore method, and displays as: The method courseScore(int, int, int) in the type GradeCalc is not applicable for the arguments (). Any help is appreciated!
import java.util.*;
public class GradeCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int overAll;
int midtermScore;
int finalsScore;
hwpoints();
midTerm();
courseScore();
}
public static int hwpoints() {
int x;
int hwTotal = 0;
int pointsPossible = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of assignments:");
x = input.nextInt();
for(int i = 1; i <= x; i++) {
System.out.println("Enter assignment score:");
int hwScore = input.nextInt();
hwTotal += hwScore;
System.out.println("Enter total possible points:");
int points = input.nextInt();
pointsPossible += points;
}
int overAll = (hwTotal / x);
System.out.println("You got " + hwTotal + " out of " + pointsPossible + ". Your overall Homework grade is a: " + overAll);
return overAll;
}
public static int midTerm() {
int midtermPoints;
int midtermPossible;
int midtermScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter Midterm Score:");
midtermPoints = input.nextInt();
System.out.println("Enter total possible Midterm Points:");
midtermPossible = input.nextInt();
midtermScore = (midtermPoints / midtermPossible);
System.out.println("Your Midterm score is " + midtermScore);
return midtermScore;
}
public static int finalScore() {
int finalsPoints;
int finalsPossible;
int finalsScore;
Scanner input = new Scanner(System.in);
System.out.println("Enter Finals Score:");
finalsPoints = input.nextInt();
System.out.println("Enter total possible Finals Points:");
finalsPossible = input.nextInt();
finalsScore = (finalsPoints / finalsPossible);
System.out.println("Your Finals score is " + finalsScore);
return finalsScore;
}
public static void courseScore(int finalsScore, int midtermScore, int overAll) {
Scanner input = new Scanner(System.in);
System.out.println("What percent of your grade is the final?");
int testWeight = input.nextInt();
System.out.println("What percent of your grade is the midterm?");
int midtermWeight = input.nextInt();
System.out.println("What percent of your grade is the homework?");
int hwWeight = input.nextInt();
int testWeighted = (finalsScore * (testWeight / 100));
int midtermWeighted = (midtermScore * (midtermWeight / 100));
int hwWeighted = (overAll * (hwWeight / 100));
int courseScore = ((hwWeighted + midtermWeighted + testWeighted) * 100);
System.out.println("Your total course grade is " + courseScore);
}
}

The methods hwpoints, midTerm and finalScore all return an int value which you are not keeping
You need to do some thing like
int hwp = hwpoints ();
int mt = midterm ();
int fs = finalScoare ();
then you can pass these variable into courseScore as
courseScore (fs, mt, hwp);
Note
In this code
int testWeighted = (finalsScore * (testWeight / 100));
you are going to be undertaking integer division.
See Int division: Why is the result of 1/3 == 0?

First thing is to understand the concept of a class and a static method.
Classes have fields and methods.
Fields (variables) hold data (state) that the Methods can operate on
Each instance of a class has its own values for these fields
Methods operate on the Fields
Methods can include call parameters
Methods can also return a value
Static instances (classes, fields, and methods) are singletons
There is only one copy of them (all instances of the class share the same one)
Static Methods cannot access (non-static) fields/methods
Using this, consider creating another class that has (most) of the content of your GradeCalc class and remove the statics from them and create an instance of that class in GradeCalc. That way each method in the class can access the fields you have defined.
Here is an example of the concept based on what you have already written.
Note: You code has other structural/implementation issue and I would never implement it as shown; but, I don't want to turn this into a Java course; so, I tried to show you something that could work within the context of what you had written.
public class GradeCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Calculator calc = new Calculator (calc);
calc.hwpoints();
calc.midTerm();
calc.courseScore();
int overAll = calc.OverAll;
int midtermScore = calc.MidtermScore;;
int overAll = calc.OverAll;
}
public class Calculator {
public void OverAll;
public void MidtermScore;
public void FinalsScore;
public void hwpoints()
{
...
OverAll = overAll
}
//Do the same for the methods below
//public void midTerm();
//public void courseScore();
}

Related

How do I override an abstract method in java?

The purpose of this code is to find the amount of items one wishes to buy, the price of those items, and what the sale currently is. For a buy three get one free sale, it would look something like
1 items at 5.0; discount is 0
2 items at 5.0; discount is 0
3 items at 5.0; discount is 5.0
4 items at 5.0; discount is 5.0
The class extends an abstract class whose abstract method is computeDiscount()
However, I have no idea how to make this method function, because it won't except it as static, but if the method isn't static then I can't use it in my code!
I have no idea what to do, and I desperately need help
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy{
static Scanner input = new Scanner(System.in);
static double itemCost;
static int count = count();
static int n = getN();
static double discount = 0;
public static void main(String[] args) {
itemCost = itemCost();
for(int i = 1; i <= count; i ++) {
discount = computeDiscount(i, itemCost);
System.out.println(i + " items at " + itemCost +
"; discount is " + discount);
}
}
public static double itemCost() {
System.out.print("Enter the cost of the item: ");
itemCost = input.nextDouble();
return itemCost;
}
public static int count() {
System.out.print("How many items are you going to buy: ");
count = input.nextInt();
return count;
}
public static int getN() {
System.out.print("How many items must you buy till you got one free? ");
n = input.nextInt();
return n;
}
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}
If you want to do anything with abstraction, you can't be using static methods. Here, it's best to use instance variables combined with a factory method to do all the initilization action.
package homeFolder;
import java.util.Scanner;
public class BuyNItemsGetOneFree extends DiscountPolicy {
// Below are your fields, or instance variables. Notice the lack of static.
final double itemCost;
final int count;
final int n;
public static void main(String[] args) {
// Now you have an instance to work with.
BuyNItemsGetOneFree sale = newInstance();
for(int i = 1; i <= sale.count; i ++) {
double discount = sale.computeDiscount(i, itemCost);
System.out.println(i + " items at " + sale.itemCost +
"; discount is " + discount);
}
}
// Only the factory method can access this.
private BuyNItemsGetOneFree (double itemCost, int count, int n) {
this.itemCost = itemCost;
this.count = count;
this.n = n;
}
public static BuyNItemsGetOneFree newInstance() {
// The scanner really only needs to be used here.
Scanner input = new Scanner(System.in);
// Initilizes itemCost
System.out.print("Enter the cost of the item: ");
double itemCost = input.nextDouble();
// Initilizes count
System.out.print("How many items are you going to buy: ");
int count = input.nextInt();
// Initilizes n
System.out.print("How many items must you buy till you got one free? ");
int n = input.nextInt();
// Constructs and returns
return new BuyNItemsGetOneFree(itemCost, count, n);
}
#Override // Always add this when overriding a method.
public double computeDiscount(int count, double itemCost) {
double discount = 0;
if((count % n) == 0)
discount += itemCost;
return discount;
}
}
If you want to go a step further, there is no need for the parameters in computeDiscount as they are (from what I see) just going to reference fields already able to be used.
Spencer make all your methods static and also your main method is missing static.
it should be something like this public static void main(String [] args)

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.

Values don't change when I print them [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I am trying to call my methods within main but after entering my dollars and cents, the values don't change when I print them
import java.text.DecimalFormat;
import java.util.Scanner;
public class ChangeMachine {
public static void main(String[] args) {
System.out.println("Change is good");
int dollars = 0;
int cents = 0;
int toonie = dollars/2;
int loonie = dollars%2;
int quarter = cents/25;
int dime = (cents%25)/10;
int nickel = ((cents%25)%10)/5;
ChangeMachine.getAmountFromUser(dollars, cents);
ChangeMachine.calculateCoins(dollars, cents);
ChangeMachine.displayInvoice(dollars, cents, toonie, loonie, quarter, dime, nickel);
}
Method to input the dollars and cents
Here I'm able to enter the amount but it won't appear when I try to display it
public static void getAmountFromUser(int dollars, int cents) {
Scanner input = new Scanner(System.in);
System.out.print("How many dollars? ");
dollars = input.nextInt();
System.out.print("How many cents? ");
cents = input.nextInt();
System.out.println();
input.close();
}
Method to calculate coins
public static void calculateCoins (int dollars, int cents){
DecimalFormat df = new DecimalFormat("#0.00");
double amount = dollars + cents/100.0;
System.out.println("$"+df.format(amount)+" requires:");
//-----Bonus-----
dollars=dollars+(cents+2)/100;
cents=(cents+2)%100;
//---------------
}
Method to display coins needed
public static void displayInvoice (int dollars, int cents, int toonie, int loonie, int quarter, int dime, int nickel){
System.out.println(toonie+" Toonies");
System.out.println(loonie+" Loonies");
System.out.println(quarter+" Quarters");
System.out.println(dime+" Dimes");
System.out.println(nickel+" Nickels");
}
}
... the values don't change when I print them
Yes, they shouldn't be changed because Java is a pass-by-value language. Any primitive variable, that is passed to a method, will not be changed (you are passing just a value of this variable, a new local variable will be created for the method).
How to solve that?
returning a changed value from a method
making operations over instance variables without local variable use
writing a custom class which keeps primitives
EDIT:
When we start talking about returning multiple values from a method, possibly, our methods are built not completely good (e.g. break the single responsibility principle). In that case, we need to refactor our methods. Consider methods with a single responsibility (calculateDollars, calculateCents, displayCoin). It will help to separate your code into small logical parts and make them more independent.
EDIT 2:
Now you are bound up with variables defined in the program's beginning. They, in their turn, are bound up with values of variables at that point. Take a look how you may correct that:
public int getLoonie(int dollars) {
return dollars % 2;
}
Better? Let's call it in the displayInvoice:
System.out.println(getLoonie(dollars) + " Loonies");
or much better
System.out.println(getLoonie(userCash.getDollars()) + " Loonies");
References to parameter arguments (local variables) in Java are pass-by-value, rather than pass-by-reference.
Each method has their own set of local variable references. When you re-assign a new value to a local variable reference, this change is local to that method.
Edit:
Here's one way to do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public final class ChangeMachine {
private ChangeMachine() {
}
public static Cash getAmountFromUser() {
try(final Scanner input = new Scanner(System.in)) {
System.out.print("How many dollars? ");
final int dollars = input.nextInt();
System.out.print("How many cents? ");
final int cents = input.nextInt();
return new Cash(dollars, cents);
}
}
public static void calculateCoins(final Cash cash) {
final DecimalFormat decimalFormat = new DecimalFormat("#0.00");
final double amount = cash.getDollars() + cash.getCents() / 100.0D;
System.out.println("$" + decimalFormat.format(amount) + " requires:");
cash.setDollars(cash.getDollars() + (cash.getCents() + 2) / 100);
cash.setCents((cash.getCents() + 2) % 100);
}
public static void displayInvoice(final Cash cash) {
System.out.println(cash.calculateToonies() + " Toonies");
System.out.println(cash.calculateLoonies() + " Loonies");
System.out.println(cash.calculateQuarters() + " Quarters");
System.out.println(cash.calculateDimes() + " Dimes");
System.out.println(cash.calculateNickels() + " Nickels");
}
public static void main(final String[] args) {
final Cash cash = getAmountFromUser();
calculateCoins(cash);
displayInvoice(cash);
}
private static final class Cash {
private int cents;
private int dollars;
public Cash(final int dollars, final int cents) {
this.dollars = dollars;
this.cents = cents;
}
public int calculateDimes() {
return this.cents % 25 / 10;
}
public int calculateLoonies() {
return this.dollars % 2;
}
public int calculateNickels() {
return this.cents % 25 % 10 / 5;
}
public int calculateQuarters() {
return this.cents / 25;
}
public int calculateToonies() {
return this.dollars / 2;
}
public int getCents() {
return this.cents;
}
public int getDollars() {
return this.dollars;
}
public void setCents(final int cents) {
this.cents = cents;
}
public void setDollars(final int dollars) {
this.dollars = dollars;
}
}
}
Were you able to compile this code before? I was just checking the ChangeMachine, getAmountFromUser, and CalculateCoins methods to check them out in Notepad ++ and came up with several errors. The last two lines of code in getAmountFromUser , System.out.println(); and 'input.close();' don't seem to be necessary.
As for the other errors, I'm seeing a lot of class, interface, or enum expected errors.

Why doesn't my array work?

I'm very new to java (only been using it for 2 days now), and am trying to make a class that lets you input three numbers, and then outputs the average of all three. When the code is like this the output always equals 0 and I don't know why? I am able to get it to work if I change add "static" to all the public integers, but why do I have to do that? Is there another way I can do it without making them static?
import java.util.Scanner;
public class lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
lettuce lettuceObject = new lettuce();
int total = 0;
int average;
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
lettuceObject.getNum1();
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.getNum2();
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.getNum3();
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum1()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your first number: ");
return num1 = keyboard.nextInt();
}
public int getNum2()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your second number: ");
return num2 = keyboard.nextInt();
}
public int getNum3()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please type your third number: ");
return num3 = keyboard.nextInt();
}
}
The output is 0 because you have never initialized your num(s), you're assigning to them on get(s) which you never call - and you're trying to set them in get(s) which isn't the customary approach.
public int num1 = 3;
public int num2 = 3;
public int num3 = 3;
And you should get 3. A getter should look like
public int getNum1()
{
return num1;
}
A setter should look like
public void setNum1(int num1) {
this.num1 = num1;
}
And then you would customarily name your class Lettuce and call it from main like
Lettuce lettuce = new Lettuce();
lettuce.setNum1(10);
System.out.println(lettuce.getNum1());
You would customarily also make your fields private and access them through your mutator and accessor methods (getters and setters)
private int num1;
private int num2;
private int num3;
You could choose to create a constructor
public Lettuce(int num1, int num2, int num3) {
this.num1 = num1;
this.num2 = num2;
this.num3 = num3;
}
You could also calculate the average from "lettuce" with something like
public double average() {
return (num1 + num2 + num3) / 3.0;
}
Edit
Please don't edit your question like that. Also, consider the order of your operations. Your get methods are what set the values. So call them before you create your array!
lettuceObject.getNum1();
lettuceObject.getNum2();
lettuceObject.getNum3();
// Each of those values is 0 until you call the previous three lines.
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
System.out.println(array[0]);
System.out.println(array[1]);
System.out.println(array[2]);
As you are new I will give you some more tips they making this work.
1: The static modifier specifies that you don't need to instanciate a Class to use that attribute (variable or method ).
For example, if you have a class with one static variable:
public class Clazz {
static int variable=1;
}
You may call it without creating an instance of Clazz. System.out.println(Clazz.variable); would compile with no problems.
Otherwise, a non-staticattribute will need an Instance of Clazz to be accessed:
Clazz instanceOfClazz = new Clazz();
System.out.println(instanceOfClazz.variable);
2: The type intis native. So, when you create your array, you are passing no values, and after reading the output, your array is not updated.
3: a double variable would be more precise to store the result of an average.
4: last but not least, your getNum method could be merged into just 1 method receiving the message as parameter, so you hace a best and clear reuse of the code. That can be staticbecause it doesn't need to interact with any object of the class Lettuce (with receive as parameter all it needs to execute and return the integer sent by the user, you can assing the return outside the method)
Ps.: by notation, the class name should start with capital letter.
Your final class would look better this way:
import java.util.Scanner;
public class Lettuce
{
public int num1;
public int num2;
public int num3;
public static void main(String args[])
{
Lettuce lettuceObject = new Lettuce();
int total = 0;
double average;
lettuceObject.num1 = lettuceObject.getNum("Please type your first number: ");
System.out.println(lettuceObject.num1);
System.out.println(array[0]);
lettuceObject.num2 = lettuceObject.getNum("Please type your second number: ");
System.out.println(lettuceObject.num2);
System.out.println(array[1]);
lettuceObject.num2 = lettuceObject.getNum("Please type your third number: ");
System.out.println(lettuceObject.num3);
System.out.println(array[2]);
int array[] = {lettuceObject.num1,lettuceObject.num2,lettuceObject.num3};
for(int counter = 0; counter < array.length;counter++)
{
total = total + array[counter];
}
average = total/array.length;
System.out.println("The average of the three numbers is: " + average);
}
public int getNum(String message)
{
Scanner keyboard = new Scanner(System.in);
System.out.println(message);
return keyboard.nextInt();
}
}
Hope this helped.

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.

Categories