Increment the number by 1 whenever i call the funtion in java - 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();

Related

Recursive method works wrongly

Just wrote simple java code to print 1 - 100 using recursive method.
Below is the code snippet
public class Test
{
public static void main(String[] a)
{
printNumber(0);
}
public static void printNumber(int i)
{
if (i < 100)
{
System.out.println(i);
i = i + 1;
printNumber(i);
}
System.out.println(i);
}
}
but the code prints
0, 1, 2, ............100, 100, 99, ................1
So anyone please tell why it is printing 100,99,98.........1 and what went wrong?
EDIT
I tried the logic to print 1 - 100 in all combinations and works well for me but output should be 1 - 99(print from inside condition) and finally 100(print by last print) but output is 1 - 100 and 100 - 1.
so please tell me why 100 to 1 is printing in output.
kindly dont tell me logic because I already got result what i expected
Use this code it works because when you call printNumber (i) it call and move further. after 100 it will stop calling itself and programcounter return to previous called function thus it printing 100 to 0
public class Test
{
public static void main(String[] a)
{
printNumber(0);
}
public static void printNumber(int i)
{
if (i < 100)
{
System.out.println(i);
i = i + 1;
printNumber(i);
}return;
}
}
just remove the second print statement like this:
public static void printNumber(int i)
{
if(i<=100)
{
System.out.println(i);
i = i + 1;
printNumber(i);
}
}
The recursive works as it is supposed to do
Each time you call printNumber(i); you're going up in the call stack, whenever you stop calling it, in this case when 1 = 100, it'll unstack and finish the code inside printNumber(), in this case, the rest of the code (after the recursive call ) is another print.
Each of those stacked calls have a different value for i since java is pass by value :
When I say pass by value it means whenever caller has invoked the
callee the arguments(ie: the data to be passed to the other function)
is copied and placed in the formal parameters (callee's local
variables for receiving the input). Java makes data communications
from one function to other function only in a pass by value
environment.
So it calls the prinln with each of those values ( 100..1 ) note that it does not do the first ( 0 ) since it has been incremented to 1 .
Nothing went wrong. The frist system out prints the accessing value at the method.
So it print the value before invoke printNumber() then when
the i value reach 101 the 101th printNumber method ends and the thread come back to the method invked before. So the second System out print the value of i of the specific method.
public class Test
{
public static void main(String[] a)
{
printNumber(0);
}
public static void printNumber(int i)
{
if(i<=100)
{
System.out.println(i);
i+= 1;
printNumber(i);
}
}

Lexicographic quicksort algorithm

My professor gave me a code for the methods to be used in sorting an array of names lexicographically, but I have no idea how what to write inside the main class to show that the program works. I am very new to java, so please if you know how to do this could you write it as simple as possible for me to understand it. Thanks in advance.
This is are the classes
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
private static void sort(String[] string, int leftlimit, int rightlimit) {
if (rightlimit > leftlimit)
{
int midpoint = partitionstep(string, leftlimit, rightlimit);
sort(string, leftlimit, midpoint - 1);
sort(string, midpoint, rightlimit);
}
}
public static int partitionstep(String[] string, int leftlimit, int rightlimit)
{
String midpoint = string[rightlimit];
int lpointer = leftlimit;
int rpointer = rightlimit;
String temp = "";
while(string[lpointer].compareTo(midpoint) <= 0)
{
lpointer = lpointer ++;
}
while(string[rpointer].compareTo(midpoint) > 0)
{
rpointer = rpointer --;
}
if(lpointer > rpointer)
{
temp = string[lpointer];
string[lpointer] = string[rightlimit];
string[rpointer] = temp;
System.out.println(string);
}
while(lpointer < rpointer)
{
temp = string[lpointer];
string[lpointer] = string[rightlimit];
string[rightlimit] = temp;
}
return lpointer;
}
}
This is the main class (as you can see I have no idea what to write)
package quicksort;
public class Quicksort {
public static void main(String[] args) {
}
}
Write something that sets up an array of strings and calls sort against it, then prints out the results or checks them against a known good result.
Ideally, write something which does this repeatedly, with particular emphasis on checking unusual combinations (already sorted or sorted in reverse, null in the array, same value appearing several times or all values being identical...)
If you want to go beyond that, you need to dig into the code to understand its edge cases and specifically test those, and/or do a "code coverage" analysis (there are tools to help with that) to make sure all parts of the code have been exercised.
Assume the algorithm of sort method is correct:
1. If the main method is within the body of quicksort_class, you can directly call the sort method as sort(arrayToBeSorted, 0 , arrayToBeSorted.length-1). And the arrayToBeSorted should ordered lexicographically after your call. You can check that to confirm.
2. If the main method is in other class, as your main method currently, you need to at least change the private prefix of sort method to public, and call quicksort_class.sort(arrayToBeSorted, 0 , arrayToBeSorted.length-1).
Some tips:
1. Private prefix of method definition means this method can only be called inside current class body.
2. Static prefix of method definition means you should call this method via class name directly, instead of via a instance of class.
By the way, can you provide what the array1 attribute stands for? I don't get why it's there.

How to pass information through a method and returning a value

I'm new to Java, and need help. I have been asked to write a program that rolls dice and determines the chance of the player to get two "1s" on the top face of the dice. I have different functions such as role(), getTopFace() etc. I want to be get what the number on the dice is using these functions, but don't know how to call them in my main function. Here's my code:
import javax.swing.JOptionPane;
import java.util.Random;
public class SnakeEyes {
private final int sides;
private int topFace;
public static void main(String[]args)
{
String numberSides;
int n;
numberSides=JOptionPane.showInputDialog("Please enter the number of sides on the dice:");
n = Integer.parseInt ( numberSides);
int[]die=new int[n];
for (int index=0; index<n;index++)
{
die[index]=index+1;
}
//Here is where I want to get information from my functions and calculate the ods of getting two 1's.
}
public void Die(int n)
{
if(n>0)
{
int sides=n;
topFace=(int)(Math.random()*sides)+1;
}
else{
JOptionPane.showMessageDialog(null, " Die : precondition voliated");
}
}
public int getTopFace(int topFace)
{
return topFace;
}
public int role(int[] die)
{
topFace=(int)(Math.random()*sides)+1;
return topFace;
}
}
Make an object of your class SnakeEyes in your main method, and call the required functions using that object.
Example:
SnakeEyes diceObj = new SnakeEyes();
int topFace = diceObj.role(n,....);
If you want to call this functions from main this functions must be "static", because main its a static function and static function can only call other static functions.
But... this is a very ugly design for a java program, before jumping to write java code you need to understand at least a little about object orientation. For example, why you can't call a non-static function from a static function?, the answer of this question requires knowledge about object orientation and its a knowledge you need if you want to write serious java code.

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 tell if a method is being called?

How can I tell if a method is being called so that I can add a counter to measure the total calls of this method?
Edit for clarification.
assuming that I have
class anything{
public String toString() {
++counter;
return "the time this method is being called is number " +counter;
}
}//end class
and I am creating an instance of anything in a main method 3 times,
and the output I want if I call its toString() the whole 3 times is this:
the time this method is being called is number 1
the time this method is being called is number 2
the time this method is being called is number 3
I want the counter being added succesfully inside the class and inside the ToString() method and not in main.
Thanks in advance.
You can use a private instance variable counter, that you can increment on every call to your method: -
public class Demo {
private int counter = 0;
public void counter() {
++counter;
}
}
Update : -
According to your edit, you would need a static variable, which is shared among instances. So, once you change that varaible, it would be changed for all instances. It is basically bound to class rather than any instance.
So, your code should look like this: -
class Anything { // Your class name should start with uppercase letters.
private static int counter = 0;
public String toString() {
++counter;
return "the time this method is being called is number " +counter;
}
}
The best way to do this is by using a private integer field
private int X_Counter = 0;
public void X(){
X_Counter++;
//Some Stuff
}
You have 2 options...
Count the messages for one instance:
public class MyClass {
private int counter = 0;
public void counter() {
counter++;
// Do your stuff
}
public String getCounts(){
return "The time the method is being called is number " +counter;
}
}
Or count the global calls for all created instances:
public class MyClass {
private static int counter = 0;
public void counter() {
counter++;
// Do your stuff
}
public static String getCounts(){
return "the time the method is being called is number " +counter;
}
}
It depends on what your purpose is. If inside you application, you want to use it, then have a counter inside every method to give details.
But if its an external library, then profilers like VisualVM or JConsole will give you number of invocations of each method.

Categories