I have just started to learn java so my question might be funny to most of you,
i am trying to write a program that calculate an average for an array of courses
and for some reason my accumulator is not incrementing
public void setStudents() {
accumulator=0;
for(int x=0;x<course.length;x++)
{
accumulator =accumulator+ course[x].result;
}
}
public double getAverage () {
average=(double)(accumulator/course.length);
return average;
}
public int getTotal() {
return accumulator;
}
I'm assuming this is wrapped in a class with a member field variable called accumulator. In this case, when the class is constructed, the setStudents method should be called, so that the accumulator is properly set. If you don't call the setStudents method in the constructor, or anywhere before you call the getAverage method, the accumulator field will just be set to its default value, which is 0. This is probably the reason why you are getting 0 as the result. This can be fixed by calling setStudents in the constructor of this class, or anywhere before you call the getAverage method. Also, in the getAverage method, you should be casting to double before doing the arithmetic, or else the integer division still gets called and then gets cast to a double afterward. So the line
average=(double)(accumulator/course.length);
should be
average=(double)(accumulator)/course.length;
class Mine {
int accumulator;
double average;
Course[] course = {Course.builder().result(10).build(), Course.builder().result(20).build(), Course.builder().result(30).build()};
public static void main(String[] args) {
Mine obj=new Mine();
obj.setStudents();
double avg = obj.getAverage();
System.out.println(avg);
}
public void setStudents() {
Course[] course = {Course.builder().result(10).build(), Course.builder().result(20).build(), Course.builder().result(30).build()};
for (int x = 0; x < course.length; x++) {
accumulator = accumulator + course[x].result;
}
}
public double getAverage() {
average = (double) (accumulator / course.length);
return average;
}
public int getTotal() {
return accumulator;
}
}
#Builder
#Data
class Course {
int result;
}
If you see above code, i had just modified your existing code.
You made some minor mistake with getting and assigning local variables.
Just go through with this link, which will guide you about scope,global variable, local variables
Related
My assignment is to create a class to count, sum, and average a series of numbers. The specifications for the class AverageCalculator are:
instance variable of type int for the running sum that have been given to the AverageCalculator
instance variable of type int for the count of numbers that have been given to the AverageCalculator
no argument constructor: AverageCalculator()
a mutator method to add a number to the AverageCalculator: void add(int newNum)
an accessor method to return the sum of all the numbers added to the AverageCalculator: int getSum()
an accessor method to return the count, or number, of numbers added to the AverageCalculator: int getCount()
an accessor method to return the average of all numbers added to the AverageCalculator - note that the instance variables are int, and the return type is double, if no numbers have been added to the object, return 0: double getAverage()
Write a class, AverageCalculatorMain that contains a main method and does the following:
create a AverageCalculator object, add one number ot the AverageCalculator, print sum, count, and average
create another AverageCalculator object. Add three numbers, print sum, count, and average
This is what I have so far:
public class AverageCalculator {
private int sum;
private int count;
public AverageCalculator() {
sum = 0;
count = 0;
}
public void add(int newNum) {
this.sum = this.sum + newNum;
count++;
}
int getSum() {
return sum;
}
int getCount() {
return count;
}
double getAverage() {
return sum / count;
}
}
This is what I have for the main method:
public class AverageCalculatorMain {
public static void main(String[] args) {
AverageCalculator average = new AverageCalculator(90);
System.out.println("The sum is " + average.getSum() + "\nThe count is " + average.getCount() + "\nThe average is " + average.getAverage());
}
}
However, when I try to create the new object (AverageCalculator average = new AverageCalculator(90);), there is an error saying it is undefined. How can I create this object and pass its value(s) successfully?
The problem is that you are trying to create an object using parametrised constructor
AverageCalculator average = new AverageCalculator(90);
But you don't have parametrised constructor in your AverageCalculator class.
So change it to
AverageCalculator average = new AverageCalculator();
OR
create a parametrised constructor.
public AverageCalculator(int count) {
this.count = count;
}
Or as per your need, you can create with two parameters i.e sum and count
EDIT:
You can have setter method
public void setCount(int sum) {
this.sum = sum;
}
And after object creation, you can call this method to set the value.
Define two constructors in your class ,
the no arg constuctor
and the one arg constructor
public AverageCalculatorMain(){}
public AverageCalculatorMain(int x){
sum = x;
}
If you intend to pass an unknown number of arguments at run time then you should use varargs constructor
public AverageCalculatorMain(int ...x){
}
or better still pass a collection as an argument to your constructor
I'm trying to check if a number is a square, and if a number is triangular.
The issue is happening at sqrt(num) which is returning 0 for all numbers I test.
I'm using an online compiler, tried several compilers, so it's not a compiling issue. Tried to declare num as a double and as an int, same results.
I'm new to Java, but not new to programming, I searched online, checked my code several times, everything looks fine, it even worked as expected before adding the variables for checking triangular number, but after declaring the variables checkTri and checkTriSqr, this started to happen. I'm sure this have nothing to do with declaring these variables (almost sure), could anyone please help me understand what's going on here?
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
public class Parent{
public static void main(String[] args){
class Number
{
public int num ;
double numSqr = sqrt(num );
double roundNumSqr = round(numSqr) ;
double checkTri = 8 * num + 1 ;
double checkTriSqr = sqrt(checkTri) ;
public void prinTest()
{
System.out.println(num);
System.out.println(numSqr);
System.out.println(roundNumSqr);
System.out.println(checkTri);
System.out.println(checkTriSqr);
}
public boolean isSqr()
{
if (numSqr == roundNumSqr)
{
return true;
}
else
{
return false;
}
}
public boolean isTriangular(){
if (checkTriSqr * checkTriSqr == checkTri )
{
return true;
}
else
{
return false;
}
}
}
Number number = new Number();
number.num = 350;
number.prinTest();
System.out.println(number.isSqr());
System.out.println(number.isTriangular());
}
}
EDIT: The following screen shot is from the tutorial I'm following, concerning declaring classes within methods!
This:
public int num ;
double numSqr = sqrt(num );
initialises num to 0 upon instance construction (the default value for an integer in the absence of assignment), and numSqr is set immediately afterwards (to zero).
You need to recalculate the sqrt() each time you subsequntly set num (perhaps by providing a method setNum() and recalculating everything within that method)
I wouldn't call your class Number, btw. There's already a Number class in the standard Java class set.
numSqr is created in the constructor, whereas number.num = 350;is declared after the construction of your object.
You can use a constructor like this :
public Numer(int num){
this.num=num;
this.numSqr=sqrt(num)
//.... ... ...
}
You can also use an empty constructor and a setter to set the number attribute :
public void setNumber(int num){
this.num=num;
this.numSqr=sqrt(num)
//.... ... ...
}
The values numSqr, roundNumSqr, etc, are all set at the point of the object's creation, however you don't set num to anything until after the object is created. The result is that, for instance,
At creation:
num = 0
therefore
numSqr = 0
roundNumSqr = 0
etc
Then, you set num = 350
But you don't reset the values of numSqr, etc, so this is still the case:
numSqr = 0
roundNumSqr = 0
You need to make a constructor for this class that takes in the value of num and then sets all of the corresponding values, so that they're only set after num has been set (or, add a "calculate" function that updates all the values).
You can modify in this way and compare with technology you have worked on .
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
public class Number {
public int num = 0;
public void prinTest() {
System.out.println(this.num);
System.out.println(this.getSqrt(this.num));
System.out.println(this.getCheckTri());
}
private double getSqrt(double value) {
return sqrt(value);
}
public boolean isSqr() {
if (this.getSqrt(this.num) == round(this.getSqrt(this.num))) {
return true;
} else {
return false;
}
}
private double getCheckTri() {
return 8 * this.num + 1;
}
public boolean isTriangular() {
if (this.getSqrt(this.getCheckTri()) * this.getSqrt(this.getCheckTri()) == this.getCheckTri()) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Number number = new Number();
number.num = 49;
number.prinTest();
System.out.println(number.isSqr());
System.out.println(number.isTriangular());
}
}
You should read some basic tutorials as you have added class inside main method,which means you need more time to check out the syntax.
The other answers alreade said, that the field num was not set to the input number, and that the other fields were actually evaluated on object creation, and hence zero too.
The purpose however is achieved by simple functions:
public static boolean isSquare(int num) {
int root = (int) Math.round(Math.sqrt(num));
return root*root == num;
}
public static boolean isCubic(int num) {
int root = (int) Math.round(Math.cbrt(num));
return root*root*root == num;
}
This exploits the cubic root.
As a comparison of doubles, a sqrt result and its rounded long value are still imprecise, I prefer to recalculate the original parameter.
public int num ;
double numSqr = sqrt(num);
By default, declared instance integer variables (variables declared inside class body) are initialized with 0 (zero). Hence, your code does nothing but take a square root of zero, which is zero.
I have the following class in java :
public class Percentage
{
private double n;
Percentage (double n )
{
this.n=n;
}
public void setN()
{
this.n=n;
}
public double getN()
{
return n;
}
public double percntage ()
{
return this.n/100;
}
}
this Class Percentage will return a double value, but the problem is we can't make any mathematic operation with values like below:
public static void main (String args[])
{
Percentage p = new Percentage(5);
double b=1;
b=p*12; // this is error because the class Percentage in not of type double
}
is there someway to make Percentage of type double ?
That is an error because you are multiplying the Percentage object with double value.
The alternative is
public static void main (String args[])
{
Percentage p = new Percentage(5);
double b=1;
b=p.getN()*12;
}
You cannot make the class type double. You can perform your operation in the n value instead.
b = p.getN()*12;
you can't define a class as double, because double is a primitive type. What you can do is what the others user suggested:
p.getN();
It will return the double value you need.
No, you can't make it behave like a double, but (like BigDecimal) you can supply methods for performing the relevant operations.
Since your code seems to imply that n = 10 means 10%, i.e. a factor of 0.10, you could make methods like these:
public double of(double value) {
return value * this.n / 100d;
}
public double add(double value) {
return value * (100d + this.n)) / 100d;
}
and then use it like this:
Percentage p = new Percentage(10);
double input = 55;
double d1 = p.of(input); // 10% of 55 = 5.5
double d2 = p.add(input); // 55 + 10% = 60.5
Given the following example code, please help me answer the following questions with hints
public class Coin
{
private String myColor;
private int mySideOne;
private double mySideTwo;
public Coin(String Color, int SideOne, double SideTwo)
{
myColor= Color;
mySideOne = SideOne;
mySideTwo = SideTwo;
}
//accessors getColor(), getSideOne(), and getSideTwo()
}
public class Total
{
private int myNumCoins;
private Coin[] moneyList;
//constructor
public Total(int myCoins)
{
myNumCoins = numCoins;
moneyList = new Coins[numCoins]
String color;
int mySideOne;
double mySideTwo;
for (int i = 0; i<numCoins; i++)
{
}
}
**
Question:
**
//Returns total amount for Coins
public double totalMoney()
{
double total = 0.0;
/* code to calculate
return total;
}
}
Which represents correct / code to calculate amount */ in the totalMoney method?
A. for (Coin t: moneyList)
total+= moneyList.getSideTwo();
B. for (Coin t: moneyList)
total+=t.getSideTwo();
I think A is right because the "t" in B. doesn't exist in the code. How am I wrong?
Let's evaluate the code using A.:
public double totalPaid()
{
double total = 0.0;
for (Ticket t:tickList)
total+= tickList.getPrice();
return total;
}
tickList is an array of Tickets. An array is an object which only has a static final field called length. So, tickList cannot have getPrice. This means, option A doesn't compile.
Let's evaluate the code using B.:
public double totalPaid()
{
double total = 0.0;
for (Ticket t:tickList)
total+=t.getPrice();
return total;
}
Here you state:
I think A is right because the "t" in B. doesn't exist in the code. How am I wrong?
In fact, t is a variable declared and used in the enhanced for loop statement. t is from type Ticket and it will take the value of each Ticket object reference stored in tickList. The enhanced for loop can be translated to this form for arrays:
for (int i = 0; i < tickList.length; i++) {
Ticket t = tickList[i];
//use t in this scope
//in this case, it's used to accumulate the value of total
total += t.getPrice();
}
Which makes B as the solution for this problem.
The answer is B because you declare t in your loop when you say Ticket t. The loop iterates the ticketList and t will stand for each Ticket in the list.
I have two different types of Sets that need to be iterated and one of the values of the objects of the set need to be summed. How can I do this with Generics, i.e without writing two summing methods for each type of Set?
private Double calculateFooScoreSum(final Set<Foo> fooScoreSet)
{
Double sum = 0.0;
for (final Foo score : fooScoreSet)
{
sum += score.getScore();
}
return sum;
}
private Double calculateBarScoreSum(final Set<Bar> barScoreSet)
{
Double sum = 0.0;
for (final Bar score : barScoreSet)
{
sum += score.getScore();
}
return sum;
}
How can I write the above two methods using Generics as a single method. Something Like:
private static Double calculateScoreSum(Set<?> scoreSet)
{
Double sum = 0.0;
for(Object scoreObj : scoreSet){
//Some casting magic
sum+=score.getScore();
}
return sum;
}
If it helps, getScore() method exists in both classes Foo and Bar.
Any ideas and suggestions are much appreciated.
Thanx
Define a common interface, say Scorable:
public interface Scorable {
int getScore();
}
And implement it with Foo and Bar:
public class Foo implements Scorable {
public int getScore () { return 1; }
}
public class Bar implements Scorable {
public int getScore () { return 2; }
}
And then, define a method that can accept any kind of Scorable, using wildcards:
private static Double calculateScoreSum(Set<? extends Scorable> scoreSet) {
Double sum = 0.0;
for (Scorable score : scoreSet){
sum += score.getScore();
}
return sum;
}
Which can receive either Set<Foo> or Set<Bar> since they both implement Scorable.