Java: count number of objects created - contsructor (call to this) - java

Count No. of Created Object - Constructor
I want to count the number of objects I created.
class ctt
{
static int counter = 0;
public ctt()
{
this(2.3);
System.out.println("default ctt");
}
public ctt(double a)
{
System.out.println("Double ctt");
}
public ctt(int a)
{
this();
System.out.println("Int ctt");
counter++;
}
public static void main(String[] args)
{
ctt c1 = new ctt(4);
ctt c2 = new ctt();
System.out.println("No.of object created: "+counter);
}
}
In which constructor counter++ has to come. [ If I give counter++ in all construtor method, counter++ is incremented to 3 for first object creation itself. ]
ctt c1 = new ctt(4);
When I create c1 object, counter++ is incremented to 1.
ctt c2 = new ctt();
This c2 object is not getting incremented.
Can any give Solution to this problem!

You only need to increment the counter in c (double a ) . This is because it is called in c () and also in c (int a) which in turn call c () which subsequently calls c (double a)

This looks like a homework assignment, so I will answer it based on this. If I am wrong, please comment and I will update my answer:
Look at the places that actually increase the counter (there is only one) and then look at how the signature of this method/constructor is different from the others. That should help you understand what is going on.
If that still does not help, use a debugger starting from your calling code and step through your code.

Your constructor with integer as argument only has the statement to increment counter.
the statement ctt c1 = new ctt(4) this calls ctt(int a) and
the statement ctt c2 = new ctt(); --> calls ctt() which does not increments the counter.
If you need both your constructors to increment, you need to increment the counter in your ctt() constructor too. i.e the constructor that doesn't take any arguments.

Related

Increment the number by 1 whenever i call the funtion in java

I am trying to print the number increment by 1 whenever i call the function, but i am not able to get the solution, below is my code
The blow is the function
public class Functions<var> {
int i=0;
public int value()
{
i++;
return i;
}
}
I am calling the above function here
import Java.Functions;
public class Increment {
public static void main(String[] args)
{
Functions EF = new Functions();
System.out.println(EF.value());
}
}
Whenever i run the program , i am getting only the output as 1 , but i want the output to be incremented by 1 . Could you please help. Thanks in Advance.
I believe your answer is with the scope of your variables and your understanding of them. You only call the method once in your given examples, so 1 is arguably the correct answer anyway. Below is a working example which will persist during runtime one variable and increment it every time a function is called. Your methods don't seem to follow the common Java patterns, so I'd recommend looking up some small example Hello, World snippets.
public class Example{
int persistedValue = 0; // Defined outside the scope of the method
public int increment(){
persistedValue++; // Increment the value by 1
return persistedValue; // Return the value of which you currently hold
// return persistedValue++;
}
}
This is due to the scope of "persistedValue". It exists within the class "Example" and so long as you hold that instance of "Example", it will hold a true value to your incremented value.
Test bases as follows:
public class TestBases {
static Example e; // Define the custom made class "Example"
public static void main(String[] args) {
e = new Example(); // Initialize "Example" with an instance of said class
System.out.println(e.increment()); // 1
System.out.println(e.increment()); // 2
System.out.println(e.increment()); // 3
}
}
If your desire is out of runtime persistence (the value persisting between application runs) then it would be best to investigate some method of file system saving (especially if this is for your Java practice!)
Your main problem is to increment the number value 1.
But you are calling your function only once. Even though you call the function many times you will get the value 1 only because it is not static variable so it will every time initialize to 0.
So please check below answer using static context.
Functions.java
public class Functions{
static int i=0;
public int value()
{
i++;
return i;
}
}
Increment.java
public class Increment{
public static void main(String []args){
Functions EF = new Functions();
System.out.println(EF.value());
System.out.println(EF.value());
System.out.println(EF.value());
}
}
Output:
1
2
3
If you design multi-threaded application, it will be better to use AtomicInteger.
The AtomicInteger class provides you an int variable which can be read and written atomically.
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();

How to use a recursive method that has a return type void in java?

So I understand how to use a recursive method that has some other return type other than void. Typically I would call the same method again in the same method( inside the recursive case), while decremented or increment some value in the call to reach the base case. Then at some point the base case is reached and the problem is solved, so it starts returning the value from every call. Along those lines.
BUT
What if the method has the return type void, so you can't call the method as it won't/can't return anything? I'm trying to write a sentence backwards, which I've solved both with a for loop and a resucrive method that can return a string value, but I'm not sure how to approach it if it's void which is what the assignment is asking for.
Edit: I should also mention the sentence can only be passed in the parameter
Thank you everyone for the information and the help!
Recursion doesn't work only with methods/functions that return values. Recursion means only that the method/function calls itself.
You must guarantee that there is at least one stop condition but this does not require the function to return a value. This is commonly achieved by incrementally changing one or more arguments that you pass each time the function recursively calls itself. When that/those arguments satisfy a certain condition your function no longer calls itself and all pending operations are solved.
I am not fully aware of the task you are trying to do but here is an example of a recursive function that writes a string backwards. I use PSEUDO-functions with names that hopefully are self-explanatory.
public void writeBackwards(String str) {
// This is the negation of the stop condition, so the stop condition
// is when the string is empty, in which case this function will do
// nothing:
if (!str.isEmpty()) {
char firstCharacter = str.getFirstCharacter();
str = str.removeFirstCharacter();
writeBackwards(str); // the recursive call
// The following operation will be pending, waiting for the
// recursive call to be resolved first:
writeCharacter(firstCharacter);
}
}
You can use any mutable Object as a parameter of the recursive function to store the result. For example, the backwards-sentence problem you mentioned could be written as:
public void stringReverse(String s, int index, StringBuilder sb) {
if (index < 0)
return;
sb.append(s.charAt(index));
stringReverse(s, index - 1, sb);
}
And called like this
StringBuilder sb = new StringBuilder();
stringReverse(mySentence, mySentence.length() - 1, sb);
Just like in C++ you can pass in pointers, here in Java you can simply pass in a class object to your function to hold the value generated from the recursive calls of the function. A simple example reflecting your question to compute fibonacci number is following.
public class ComputeFibonacci {
static class Fibonacci {
public int ith;
public int value;
Fibonacci(int a, int b) {
ith = a;
value = b;
}
}
private static void fibonacci(Fibonacci result) {
if (result.ith == 1 || result.ith == 2) {
result.value = 1;
} else {
Fibonacci left = new Fibonacci(result.ith - 1, 0);
Fibonacci right = new Fibonacci(result.ith - 2, 0);
fibonacci(left);
fibonacci(right);
result.value = left.value + right.value;
}
}
public static void main(String[] args) {
// Here we compute the 10th fibonacci number
Fibonacci f = new Fibonacci(10, 0);
fibonacci(f);
System.out.println("The result is " + f.value);
}
}
Good luck.

improve calling next method in JAVA

I'm looking for a better way to organize my class.
Right now my code looks like this:
mainMethod:
-number1 input
-call method1 with number1 als value
method1:
-do "stuff" with input
-call method2 with new "stuff" as value
method2:
-do stuff
-call method3
etc...
So i start with user input in my main method and my whole class works like domino, the first method needs to be called to run the next method.
I would rather have method1 return a value and save it in some global variable in my class which can be used by method2 and so on.
Here is my Code with exactly this problem: (it calculates sqrt)
package wurzel;
import java.util.Scanner;
import wurzel.Fraction;
public class wurzel {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Eingabe:");
int in = s.nextInt();
s.close();
bisection(in);
}
private static int bisection(int N){
int counter = 0;
for(int i = 0; i < N;i++){
if((counter*counter) > N){
counter--;
break;
}
else if(counter*counter == N){
break;
}
else counter++;
}
calculateSequence(counter,N);
return counter;
}
static int[] calculateSequence(int vKomma, int look){
int m = 0;
int d = 1;
int a = vKomma;
int[] intarr = new int[4];
intarr[0] = vKomma;
for(int i = 1; i <= intarr.length; i++){
if(i == intarr.length )
break;
else{
m = (d*a) - m;
d = (look - (m*m)) / d;
a = (vKomma + m) / d;
intarr[i] = a;
}
}
calculateApproximation(intarr);
return intarr;
}
static double calculateApproximation(int[] sequence ){
Fraction result = new Fraction((sequence.length)-1);
for(int dcounter = sequence.length; dcounter > 0; dcounter--){
result = result.reciprocal().add(sequence[dcounter-1]);
}
System.out.println("Approximation als double: " +result.doubleValue());
System.out.println("Approximation als Bruch: " +result);
return result.doubleValue();
}
}
You should also seperate code into different classes. E.g. have a generic MathHelper class which has these methods in it.
This helps keep code seperate and easy to read.
You mentioned that you wanted to store some data in a global variable for the class as a whole. The way to do this is by making the class use instance methods rather than class methods. With class methods, you have to use class variables. But, when you use instance methods, you can define instance variables which can be accessed by any method within the class.
To do this, change all your methods (apart from main()) by removing the keyword static from each method. Then, define the instance variable that is global for the class. e.g. if your global variable is of type int then it would be:
private int myInstanceVariable;
This instance variable, or global variable, can be accessed by a getter and setter.
It is quite normal methods to call each other and to form long chains of calls.
So I would not worry about that. Actually in real world, in enterprise code,
you have call stack going through tens of calls. So I think global variables would
be worse practice compared to what you did.

Getting value to display for Java CurrentAccount class

package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.

How can I reset all object values with only one method call?

Basically, I want to create Counter objects, all they have to do is hold number values. And in my resetCounters method, I would like to reset each object's values. This is probably very easy, but I'm a newb.
public class Counter
{
Random number = new Random();
Counter()
{
Random number = new Random();
}
public Random getNumber()
{
return number;
}
public void setNumber(Random number)
{
this.number = number;
}
public static void main(String[] args)
{
Counter counter1 = new Counter();
Counter counter2 = new Counter();
Counter counter3 = new Counter();
Counter counter4 = new Counter();
Counter counter5 = new Counter();
}
public static void resetCounters()
{
}
}
First option: Memorize each instance of Counter.
Collect each instance of Counter in some static collection.
To reset all, simply iterate over all items in the collection.
But strong references are too strong for this -- make sure it's a collection of weak references.
Remarks:
Using weak references will avoid the issue that the Counter objects exist indefinitely only because of their reference from within the static collection. Objects that are referred to only by weak references are eventually collected by the garbage collector.
The collection of every instance can be achieved by declaring the Counter constructor private and allowing only construction through a static member function which will also do the registration. (Or use some other incarnation of the Factory pattern.) I believe a factory is the way to go here, since each construction of an object has to carry out also a side effect. But perhaps it will make do to have the Counter constructor register this with the static collection.
Second option: Generation counter
Keep a static generation counter of type long, and also a copy of this counter in each instance. When resetting all counters, just increase the static generation counter. The getNumber() method will then check the static generation counter against its own copy and reset the counter if the static generation counter has changed.
(I don't really know the "official" name for this trick. How to zero out array in O(1)?)
Since we have no idea what the context is, we can't narrow down the specific thing you should do is, but the options that occur to me immediately are...
1: If the counters have distinct meanings beyond "counter1, counter2, counter3," then they could be static class variables (with more useful names).
public class Counter {
static Counter counter1 = new Counter();
...
public void resetCounters() {
counter1.clear();
counter2.clear();
...
}
}
2: If you just want several distinct counters, and they have no particular meaning by themselves, and you know that there will only ever be five of them, then you should use an array:
public class Counter {
public static void main(String[] args) {
Counter[] counters = {new Counter(), new Counter(), new Counter(), new Counter(), new Counter()};
...
}
static void resetCounters(Counter[] counters) {
for (Counter c : counters) {
c.reset();
}
}
}
Or, if you're planning to have an arbitrary number of them, you might try one of the fancier factory patterns. It really depends on what the context is, what you're actually trying to do, and what the point of the exercise is.
Since you're working with a large number of objects, you would be well served placing them in some sort of collection, like an ArrayList.
List<Counter> counters = new ArrayList<Counter>();
Insert all of your counters into there using the .add() method. Then, you can author your resetCounters() method in this manner:
public static void resetCounters(List<Counter> counters) {
for(Counter c: counters) {
// perform some action to reset the counters, as described by you
}
}
1. First of all there is not need to Initialize a Random nos as an instance variable,just have a Object Reference Varaible, as you are already initializing it in the Constructor.
eg:
Random number;
2. Create an ArrayList and store all the Counter objects.
ArrayList<Counter> arr = new ArrayList<Counter>();
3. Add each counter object in to the ArrayList.
4. Make reset function Non-static..there is no need for it to be static.
5. Iterate and reset...
for (Counter c : arr){
c.reset();
}
6. In reset() do the following..
public void reset(){
this.number = 0;
}
The easiest and elegant way of achieving what you want is keeping a reference to all created objects somewhere, in a factory for example and resetting them when needed.
public class CounterFactory{
private List<Counter> counters = new ArrayList<Counter>();
public Counter createCounter(){
Counter c = new Counter();
counters.add(c);
return c;
}
public void resetCounters(){
for(Counter c : counters) c.setNumber(new Random());
}
}
And in the main method, use it this way:
public static void main(String[] args)
{
CounterFactory f = new CounterFactory();
Counter counter1 = f.createCounter();
Counter counter2 = f.createCounter();
Counter counter3 = f.createCounter();
Counter counter4 = f.createCounter();
Counter counter5 = f.createCounter();
// Reset all counters
f.resetCounters();
}

Categories