The question asks me to make a class where there are addNumber(int numbers) and sum() methods in NumberStatistics class. The addNumber method can't store any value.
public class NumberStatistics {
private int number;
private int sum;
public NumberStatistics() {
this.sum = 0;
}
public void addNumber(int numbers) {
this.number = numbers;
sum();
}
public int sum() {
this.sum = this.sum + this.number;
return this.sum-this.number;
}
}
Main:
public class Main {
public static void main(String[] args) {
NumberStatistics stats = new NumberStatistics();
stats.addNumber(3);
stats.addNumber(5);
stats.addNumber(1);
stats.addNumber(2);
System.out.println("sum: " + stats.sum());
}
}
So I have to do return this.sum-this.number; But is there other way to achieve same result?
update: edited to fix errors.
I would use this implementation:
public class NumberStatistics {
private int sum;
public NumberStatistics() {
this.sum = 0;
}
public void addNumber(int number) {
this.sum += number;
}
public int getSum() {
return this.sum;
}
}
While this is far from an ideal implementation for a basic calculator, it meets the requirement The addNumber method can't store any value. If we cannot store any state about the numbers being input, then the only option is to compute the sum on the fly. Hence, I also renamed the sum() method to getSum(), because now it simply returns the sum which is already known.
You can add the line:
this.sum = this.sum + numbers;
in the addNumber method, so you remove the need for the "number" variable, and in the sum method just return this.sum
Related
Creating two separate packages mathematics and Application. With a class called MathHelper and Application in either one. I need to add static method tothe MathHelper.java class called factorial(int) that receives one integer and returns the factorial of the number passed. A main method is added to application called and calls the Mathhelper.factorial. This is the code i have so far...
public class Application {
public static void main(String[]args) {
System.out.println(MathHelper.doubleInt((9)));
}
}
public class MathHelper {
public static void main(String[]args) {
}
public static int fact(int factNum) {
if (factNum==1) {
return 1;
}
else {
return factNum + (fact(factNum - 1));
}
}
}
You can calculate factorial using:
loops:
public long fact(int factNum) {
long fact = 1;
for (int iteration = 2; iteration <= factNum; iteration++) {
fact = fact * iteration;
}
return fact;
}
streams:
public long fact(int factNum) {
return LongStream.rangeClosed(1, factNum)
.reduce(1, (long fact, long iteration) -> fact * iteration);
}
recursion:
public long fact(int factNum) {
if (factNum <= 2) {
return factNum;
}
return factNum * fact(factNum - 1);
}
I would like to know if Java allows you to call a constructor from a different class, and perform mathematical operations on it. And return its results in the Main class.
For example, I have
public class Wallet {
private int dollar;
public Wallet(int dollar){
this.dollar = dollar;
}
I also have
public class Count {
private int counter;
private ArrayList<Wallet> wallet;
public Count(){
this.wallet = new ArrayList<Wallet>();
}
public void addWallets(Wallet dollar) {
this.wallet.add(dollar);
}
public int sum(){
return 0;}
Now, my goal is to add the amount of money in each wallet, and print the results. This is the main class.
public class Main {
public static void main(String[] args) {
Count count = new Count();
Wallet wallet1 = new Wallet(34);
Waller wallet2 = new Wallet(26);
count.addWallets(wallet1);
count.addWallets(wallet2);
System.out.println( "Total is: " + count.sum() );
}
}
Thank you for your help!
The question you asked is quite unclear. But I will try to help you.
goal is to add the amount of money in each wallet, and print the
results.
Have a getter and setter methods for dollar in your Wallet class. So that you can use them later in the program.
In sum method sum of the dollars from each Wallet.
Here is the solution:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Count count = new Count();
Wallet wallet1 = new Wallet(34);
Wallet wallet2 = new Wallet(26);
count.addWallets(wallet1);
count.addWallets(wallet2);
System.out.println("Total is: " + count.sum());
}
}
class Count {
private int counter;
private ArrayList<Wallet> wallet;
public Count() {
this.wallet = new ArrayList<Wallet>();
}
public void addWallets(Wallet dollar) {
this.wallet.add(dollar);
}
public int sum() {
int sum = 0;
for(Wallet w : wallet) {
sum += w.getDollar();
}
return sum;
}
}
class Wallet {
private int dollar;
Wallet(int dollar){
this.dollar = dollar;
}
public int getDollar() {
return dollar;
}
public void setDollar(int dollar) {
this.dollar = dollar;
}
}
In sum() method you can create object of Wallet class like Wallet wt=new Wallet(10) it will internally call the constructor of Wallet but not possible to call explicitly.You can call in super class and same class using this and super keyword.
I think you misunderstood the working of a list.
When you are running below code,
count.addWallets(wallet1);
count.addWallets(wallet2);
It adds wallet1 and wallet2 to ArrayList<Wallet> wallet of count as two separate elements.
When you are callingcount.sum(), that method will always return 0 based on your method declaration. If you want to get the sum of all elements when you are calling that method, try declaring the method as below:
public int sum(){
int total =0;
for(int i=0;i< wallet.size();i++){
total = total + wallet.get(i).getDollar();
}
return total;
}
And add setters and getters in your Wallet class for Dollar as
public int getDollar() {
return dollar;
}
public void setDollar(int dollar) {
this.dollar = dollar;
}
That way when you call the method, it gets the sum of dollars in all wallets and returns you.
How can I invoke a method and print its result?
public class Test {
public static int main (String args[]){
System.out.println(total);
}
public int numbers (int a, int b){
int total;
total = a + b;
return = total;
}
}
Try this instead:
public class Test {
public static void main (String args[]){
System.out.println(numbers(1, 2));
}
public static int numbers(int a, int b){
int total;
total = a + b;
return total;
}
}
Variables are scoped to the method or class in which they are defined, therefore the 'total' variable is accessible only in the 'numbers' method
public class Test {
public static void main (String args[]){
System.out.println(numbers(anumber,bnumber));
}
public static int numbers (int a, int b){
int total;
total = a + b;
return total;
}
I am trying to test my abstract class but I am running into problems when I call the methods from the test class. It has been a while since I used Java and I have not used abstract classes before. Any pointers on where I am going wrong would be appreciated. Thanks.
The abstract class
public abstract class RationalNumbers {
public int numerator, denominator, temp;
public void setNumerator(int n) {
numerator = n;
}
public void setDenominator(int d) {
denominator = d;
}
public int getNumerator() {
return numerator;
}
public int getDenominator() {
return denominator;
}
public int add() {
temp = numerator + denominator;
return temp;
}
public int subtract() {
temp = numerator - denominator;
return temp;
}
public int multiply() {
temp = numerator * denominator;
return temp;
}
public int divide() {
temp = numerator / denominator;
return temp;
}
public boolean isEqual() {
boolean isEqual;
if (numerator == denominator) {
isEqual = true;
} else {
isEqual = false;
}
return isEqual;
}
}
The test class
public class testClass extends RationalNumbers {
public static void main(String[] args) {
setNumerator(5);
setDenominator(10);
System.out.println("Equal: " + isEqual());
System.out.println("Numerator: " + getNumerator());
// etc...
}
}
I'm sorry to tell you this, but your attempt at creating an abstraction for a rational number is wrong in every way. It is not correct at all. None of those methods are correct: add, subtract, multiply, divide, isEqual - all are utterly incorrect.
Wouldn't you want to override equals() - and hashCode()? What made you think that isEqual() was a good idea?
Look at this for an example of how to do it properly.
I'm just beginning in programming and I'd like to make exercise from a book, but I can't. That's my problem:
public class increment {
int increment() {
return this + 1; // aka this++
}
public static void main(String[] args) {
int a = 0;
System.out.println(a.increment());
}
}
As you for sure guessed already, that it doesn't works, I want to ask you how to get outputed integer a incremented by one, but using keyword 'this'.
Regards and sorry for stupid questions.
It is strange to name a class like a method.
I guess you wanted this:
public class Counter {
int val;
public Counter (int start) {
val = start;
}
public void increment() {
val ++;
}
public String toString () {
return Integer.toString (val);
}
public static void main(String[] args) {
Counter counter = new Counter (0);
counter.increment ();
System.out.println(counter.toString ());
}
}
this is an object (the current object). You cannot "increment" it.
A way to do it is:
public class Increment {
int a = 0;
int increment() {
return a + 1;
// or: return this.a + 1;
// or: a++; return a; if you want a to be incremented from now on
}
public static void main(String[] args) {
Increment inc = new Increment();
System.out.println(inc.increment());
}
}
The this keyword in Java refers to the current scope's object instance. I don't think it's what you're looking for in this case.
In your example, a isn't an object of the class increment, it is a primitive int. In order to use the .increment() function you defined, it would have to be an object of type increment.
One option that may be what you're looking for would be the following.
public class Increment { //Java likes capitalized class names
private int myInt;
public Increment(int a) { //constructor
myInt = a;
}
public int increment() {
return ++myInt;
}
public static void main(String[] args) {
Increment a = new Increment(0);
System.out.println(a.increment());
}
}
In this example, we make a new class of type increment, which internally contains an integer. Its increment method increments that internal integer, and then returns the number.
you are using operator + for your current object (this). Operator overloading is not supported in java.
Something like this will work:
class MyInteger {
private int internal;
public MyInteger( int value ){
this.internal = value;
}
public int incerment(){
return ++this.internal;
}
}
public class Increment {
public static void main(String[] args) {
MyInteger a = new MyInteger(0);
System.out.println(a.increment());
}
}
You see, you can only implement methods for your own classes, not for existing classes, or for primitives like int.
i don't think you can use this to return the value, except if you're making a new class like this:
class Increment1
{
private int a;
public int increment2(int a)
{
this.a=a;
return this.a + 1;
}
}
public class Increment
{
static Increment1 b = new Increment1();
public static void main(String[] args)
{
int a = 0;
System.out.println(b.increment2(a));
}
}
You cannot increment a class like this.
You have to use a member variable that you can increment.
public class Test {
private int var;
public Test(int i) {
this.var = i;
}
int increment() {
this.var++;
}
}
public static void main(String[] args) {
Test t = new Test(0);
System.out.println(t.increment());
}
This refers to the current instance of the class, not a particular member.
You want to increment a property (I'm guessing of type long or int), and not the instance of your increment class (should be Increment, by the way).
Something like this would work:
public class increment {
private int innerValue = 0;
int increment() {
innerValue+=1
return innerValue; // aka this++
}
public static void main(String[] args) {
increment a = new increment()
System.out.println(a.increment());
}
}