Calculating with attributes - java

Why is the C equal to 0.
What should I do when I want calculate with the modified attributes.
Why the C calculate with the default set up variables and not with the modified ones.
public class Object{
int A;
int B;
int C=A+B;
int AddOnetoA(){
A=A+1;
return A;
}
int AddOnetoB(){
B=B+1;
return B;
}
void ShowA() {
System.out.println(A);
}
void ShowB() {
System.out.println(B);
}
void ShowC() {
System.out.println(C);
}
}
And:
public static void main(String[] args) {
Object obj =new Object();
obj.AddOnetoA();
obj.AddOnetoA();
obj.AddOnetoA();
obj.AddOnetoB();
obj.AddOnetoB();
obj.AddOnetoB();
obj.ShowA();
obj.ShowB();
obj.ShowC();
}
output:
3
3
0

C is computed only once. During the time of definition. The C=A+B gets executed during class loading time. You are updating A & B afterwards. So C stays as 0
In other words, the effect of your updates to a variable used in an expression are not retro-actively applied to those expressions.

The default values for integers which are not set is 0.
You do the following:
int A; // sets A to 0
int B; // sets B to 0
int C=A+B; // sets C to A + B = 0 + 0 = 0
The notation C=A+B doesn't mean that the value C will be updated with each update of A or B but defines only its initial value.
You have to update its value with each increment of A or B variables by yourself:
int AddOnetoA(){
A=A+1;
c = A + B; // here
return A;
}
int AddOnetoB(){
B=B+1;
c = A + B; // and here
return B;
}
Don't create an object with the name Object which is the one that each one inherits from. Use for example MyObject for this simple case.
Lastly, I highly recommend you follow the Java conventions and start the name of variables and methods with a lower-case letter, such as:
int addOnetoB(){
b = b + 1; // equal to b++;
c = a + b; // and here
return b;
}

If you want C to reflect always the sum of A+B, you can remove int C; and alter showC:
void ShowC() {
System.out.println(A+B);
}
This is a valid solutions if the effort to calculate C is low.

Related

Transformation of two integers into a double in Java

This is the task:
Implement a static-public method named "createDouble" in the class "Functionality.java". The method gets two integer values a and b as input and should transform them to a double value and return it as follows:
The first input value a, should be placed before the comma or dot.
The second input value b, should be after the comma or dot and superfluous zeros should be removed.
No imports may be used to solve this task. Also the use of the Math library or other libraries is prohibited. Implement an algorithm that contains at least one meaningful loop.
This was my idea:
public class Functionality {
public static double createDouble(int a, int b) {
double c = b;
double d = 1;
while (c >= 1) {
c /= 10;
d *= 10;
}
return a + b/d;
}
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(createDouble(12, Integer.MAX_VALUE));
}
}
The problem is I am using the Method Integer.MAX Value which I shouldn´t use. Is there another option to write this code ?
Your code looks sound, just a small tweek I would make. Your variable c will equal what you want b to be after it's done dividing so you can just use it directly. Otherwise, you don't really need to be using Integer.MAX_VALUE at all. Just use arbitrary values.
public class Functionality
{
public static double createDouble(int a, int b) {
double c = b;
while(c >= 1)
c /= 10;
return a + c;
}
public static void main(String[] args) {
System.out.println(createDouble(15, 351));
System.out.println(createDouble(32, 8452));
}
}
Output:
15.351
32.8452
Here my Implementation
public class Functionality {
private static double logb10(double num){
return (num > 1) ? 1 + logb10(num / 10) : 0;
}
public static double createOtherDouble(int a, int b) {
double c = a;
int len =(int) logb10(b);
double d = b;
for(int i = 0; i < len; i++){
d /= 10;
}
return c + d;
}
public static void main(String []args){
System.out.println(Integer.MAX_VALUE);
System.out.println(createOtherDouble(12, Integer.MAX_VALUE));
}
}

Java: About Recursive counting

I'm having some problems whit an exercise I found.
I was provided a method, and can't make any changes to it.
Inside said method, I should identify the first repeating digit, beetwen two integers, And return it's position.
For example: 1234 and 4231 results in 1.
And I managed to make it work,
It's just that it doesn't work if I try to use the method more than once, it simply keeps adding to the previous value.
This is my code so far
public static final int BASENUMERACAO = 10;
public static int indice = 0;
private static int getLowestIndexWithSameDigit(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Both numbers should positive " + a + " " + b);
} else {
if (a % BASENUMERACAO == b % BASENUMERACAO) {
return indice;
} else if (a / BASENUMERACAO != 0 && b / BASENUMERACAO != 0) {
indice++;
return getLowestIndexWithSameDigit(a / BASENUMERACAO, b / BASENUMERACAO);
} else {
return -1;
}
}
I tried passing index, as a local variavel, but it just overrides the curent value, everytime it's called, therefore only returning 0 or -1
Could someone tell me how to I do keep count in a recursive method, or just how do I identify the digit whitout a counter?
The problem is that you are retaining state from the previous invocation, in the indice variable. indice is an example of mutable global state, which is generally a bad idea for the reason you are experiencing here: you might carry over the results of previous calculations into new calculations, leading to unpredictable (or maybe unexpected) results.
Make your indice variable a parameter of the method:
private static int getLowestIndexWithSameDigit(int a, int b, int indice) {
// ...
}
So your recursive call will also pass a value for this:
return getLowestIndexWithSameDigit(a / BASENUMERACAO, b / BASENUMERACAO, indice);
To start the iteration, you can either explicitly pass 0, or you can create a method which takes just a and b:
private static int getLowestIndexWithSameDigit(int a, int b) {
return getLowestIndexWithSameDigit(a, b, 0);
}
Create another method to call your recursive method and use the vars that you need as parameter for the recursive version and keep passing them.
Something like:
private static int myMethod( int a, int b ) {
return myRecursiveMethod( a, b, 0, 0 );
}
private static int myRecursiveMethod( int a, int b, int var1, int var2 ) {
// do the recursive work...
myRecursiveMethod( newValueForA, newValueForB, var1, var2 ) {
}

Is this a recursion or not?

I have an argument with my friend because I don't think fib_2() is recursion, but he says it is because it calls itself.
I don't think it is because one fib_2() doesn't have a return result for use as an argument for another fib_2().
I think fib_2() is the same with fib_3(),it's a iteration,not a recursion.
So is it a recursion or not ?
public class Demo {
public static void main(String[] args) {
System.out.printf("fib_1 -> %d\n", fib_1(10));
System.out.printf("fib_2 -> %d\n", fff(10));
System.out.printf("fib_3 -> %d\n", fib_3(10));
}
//This is recursion
public static int fib_1(int n) {
if (n == 1 || n == 2)
return 1;
return fib_1(n - 1) + fib_1(n - 2);
}
//Is this recursion or not ?
public static int fff(int n) {
int a = 1, b = 1, c = 0, count = 2;
return fib_2(a, b, n, c, count);
}
public static int fib_2(int a, int b, int n, int c, int count) {
if (count == n) {
return c;
}
int tmp = b;
b = a + b;
a = tmp;
c = b;
++count;
return fib_2(a, b, n, c, count);
}
public static int fib_3(int n) {
int a = 1, b = 1;
for (int i = 2; i < n; i++) {
int temp = b;
b = a + b;
a = temp;
}
return b;
}
}
fff is not recursive, because it does not calls itself. It calls fib_2 which has a recursive implementation, but it is not enough to make the fff method recursive.
fib_2, on the other hand, is textbook-recursive: it has a base case for count == n, and it has a recursive branch that calls fib_2 with new values of a, b, and c.
fib_2 is recursive. fff is not.
The first call of fib_2 uses returns (hence 'uses') the result of the second call.
Or formal:
Recursion is defined by two properties:
A simple base case (or cases)—a terminating scenario that does not use recursion to produce an answer
A set of rules that reduce all other cases toward the base case
Your if inside fib_2 fulfills the first property.
The call to fib_2 fulfills the second.
fib_3 is an iterative.
fib_2 is not equal to fib_3!
Two functions are equal (in a mathematical manner), if and only if they produce the same output for every given input! fib_2 and fib_3 have different parameters so this can't be true.
fib_3 may be equal to fff and/or fib_1
For equality in a computer science manner you have to consider things like side effects.
public static int fib_2(int a, int b, int n, int c, int count) {
if (count == n) {
return c;
}
int tmp = b;
b = a + b;
a = tmp;
c = b;
++count;
return fib_2(a, b, n, c, count);
}
I think in this code recussion is happening.

How to call method in lambda expression

I have 3 ways to swap 2 variables (basically 3 different algorithms). Since you can't pass a method as a parameter in Java, I thought this would be a good time to use lambda expressions.
chooseSwapMethod(int selection) {
if(selection == 1) {
functionThatUsesSwap(
(int[] arr, int x, int y) -> {
int holder = arr[x];
arr[x] = arr[y];
arr[y] = holder;
});
}
else if(selection == 2)
{
functionThatUsesSwap(
(int[] arr, int x, int y) -> {
arr[x] -= arr[y];
arr[y] = arr[x]-arr[y];
arr[x] -= arr[y];
});
}
else if(selection == 3) {
functionThatUsesSwap(
(int[] arr, int x, int y) -> {
arr[x] = arr[x]^arr[y];
arr[y] = arr[y]^arr[x];
arr[x] = arr[x]^arr[y];
});
}
else {
throw new IllegalArgumentEarr[x]ception();
}
}
but in the method functionThatUsesSwap how do you actually use the swap? Am I not understanding lambda expressions clearly? For example
public void functionThatUsesSwap(Swaper s)
{
int[] someArr = {1, 2};
s.doSwap(someArr, 0, 1);//this is where I’m stuck
System.out.println(“a: “+someArr[0]+” b: “+someArr[1]);//this should print out a: 2 b: 1
}
Java is pass by value, that means that in the following:
int a = 5;
int b = 6;
swap(a,b);
System.out.println(a+" "+b);
There is no way for the function swap to change value of a or b and the result will always be 5 6.
What you can do is:
pass and arrays of 2 numbers into the swap method, and swap numbers inside that array.
make a class to hold 2 numbers and pass that.
Going with possibility 2:
class Pair {
int a, b;
}
#FunctionalInterface
interface Swapper {
void swap(Pair p);
}
void main() {
Pair p = new Pair();
p.a = 5;
p.b = 6;
Swapper swapper = (v -> {
v.a ^= v.b;
v.b ^= v.a;
v.a ^= v.b;
});
swapper.swap(p);
System.out.println(p.a + " " + p.b);
}
Result: 6 5. Note that your claim that you can't pass a method as a parameter in Java isn't entirely true, since you can pass interfaces instead.
EDIT:
There is yet another approach (I haven't thought of this earlier because Interger class is immutable). You can create a mutable (= changable) object vrapper for integer value, something like:
class IntVrapper {
public int value;
}
Then your swap method could swap data between those two objects.

How to write a basic swap function in Java [duplicate]

This question already has answers here:
Java method to swap primitives
(8 answers)
Closed 6 years ago.
I am new to java. How to write the java equivalent of the following C code.
void Swap(int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}
Here is one trick:
public static int getItself(int itself, int dummy)
{
return itself;
}
public static void main(String[] args)
{
int a = 10;
int b = 20;
a = getItself(b, b = a);
}
Sorting two ints
The short answer is: you can't do that, java has no pointers.
But here's something similar that you can do:
public void swap(AtomicInteger a, AtomicInteger b){
// look mom, no tmp variables needed
a.set(b.getAndSet(a.get()));
}
You can do this with all kinds of container objects (like collections and arrays or custom objects with an int property), but just not with primitives and their wrappers (because they are all immutable). But the only way to make it a one-liner is with AtomicInteger, I guess.
BTW: if your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int):
Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged.)
Parameters:
list - The list in which to swap elements.
i - the index of one element to be swapped.
j - the index of the other element to be swapped.
Sorting an int[] array
apparently the real objective is to sort an array of ints.
That's a one-liner with Arrays.sort(int[]):
int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);
To check the output:
System.out.println(Arrays.toString(arr));
// [1, 2, 3, 19, 25, 378]
And here is a simple helper function to swap two positions in an array of ints:
public static void swap(final int[] arr, final int pos1, final int pos2){
final int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
Here's a method to swap two variables in java in just one line using bitwise XOR(^) operator.
class Swap
{
public static void main (String[] args)
{
int x = 5, y = 10;
x = x ^ y ^ (y = x);
System.out.println("New values of x and y are "+ x + ", " + y);
}
}
Output:
New values of x and y are 10, 5
Use this one-liner for any primitive number class including double and float:
a += (b - (b = a));
For example:
double a = 1.41;
double b = 0;
a += (b - (b = a));
System.out.println("a = " + a + ", b = " + b);
Output is a = 0.0, b = 1.41
There are no pointers in Java. However, every variable that "contains" an object is a reference to that object. To have output parameters, you would have to use objects. In your case, Integer objects.
So you would have to make an object which contains an integer, and change that integer. You can not use the Integer class, since it is immutable (i.e. its value cannot be changed).
An alternative is to let the method return an array or pair of ints.
In cases like that there is a quick and dirty solution using arrays with one element:
public void swap(int[] a, int[] b) {
int temp = a[0];
a[0] = b[0];
b[0] = temp;
}
Of course your code has to work with these arrays too, which is inconvenient. The array trick is more useful if you want to modify a local final variable from an inner class:
public void test() {
final int[] a = int[]{ 42 };
new Thread(new Runnable(){ public void run(){ a[0] += 10; }}).start();
while(a[0] == 42) {
System.out.println("waiting...");
}
System.out.println(a[0]);
}
What about the mighty IntHolder? I just love any package with omg in the name!
import org.omg.CORBA.IntHolder;
IntHolder a = new IntHolder(p);
IntHolder b = new IntHolder(q);
swap(a, b);
p = a.value;
q = b.value;
void swap(IntHolder a, IntHolder b) {
int temp = a.value;
a.value = b.value;
b.value = temp;
}
Snippet-1
public int[] swap1(int[] values) {
if (values == null || values.length != 2)
throw new IllegalArgumentException("parameter must be an array of size 2");
int temp = values[0];
values[0]=values[1];
values[1]=temp;
return values;
}
Snippet-2
public Point swap2(java.awt.Point p) {
if (p == null)
throw new NullPointerException();
int temp = p.x;
p.x = p.y;
p.y = temp;
return p;
}
Usage:
int[] values = swap1(new int[]{x,y});
x = values[0];
y = values[1];
Point p = swap2(new Point(x,y));
x = p.x;
y = p.y;
Java uses pass-by-value. It is not possible to swap two primitives or objects using a method.
Although it is possible to swap two elements in an integer array.
You cannot use references in Java, so a swap function is impossible, but you can use the following code snippet per each use of swap operations:
T t = p
p = q
q = t
where T is the type of p and q
However, swapping mutable objects may be possible by rewriting properties:
void swap(Point a, Point b) {
int tx = a.x, ty = a.y;
a.x = b.x; a.y = b.y;
b.x = t.x; b.y = t.y;
}
You have to do it inline. But you really don't need that swap in Java.
Your swap function is essentially changing the values in two pieces of memory. Anything referencing those bits of memory will now get different values.
In Java there aren't really pointers, so this won't work. Instead, references are held on objects, and you can only change stuff inside the objects. If you need to reference one object in two places, so that you can pass the same values around the system and have things react to them changing, try something like the repository pattern or dependency injection.
We can only guess at why you needed this code in C. The only advice I can give is to think about the changes to the objects which you want to achieve, preferably add a method on the actual objects rather than pulling their internals out, and call that method instead. If this doesn't help you, try posting the calling code as we'll probably have a good idea of how to solve the real problem Java-style.
Java is pass by value. So the swap in the sense you mean is not possible. But you can swap contents of two objects or you do it inline.
You can swap variables with or without using a temporary variable.
Here is an article that provides multiple methods to swap numbers without temp variable :
http://topjavatutorial.com/java/java-programs/swap-two-numbers-without-a-temporary-variable-in-java/
You can easily write one yourself.
given:
int array[]={1,2};
you do:
int temp=array[0];
array[0]=array[1];
array[1]=temp;
And you're done. 3 lines of code.
Swapping by using pointer is not possible in java. However, you can implement swapping by passing array containing two objects.
Code goes like this:
public class Swap {
public static void swap(String [] a){
String temp;
temp = a[0];
a[0] = a[1];
a[1] = temp;
}
public static void main(String [] args){
String [] foo = new String[2];
foo[0] = "str1";
foo[1] = "str2";
swap(foo);
System.out.println("First value: "+ foo[0]);
System.out.println("Second value: "+ foo[1]);
}
}
Output:
First value: str2
Second value: str1
public class swaptemp {
public static void main(String[] args) {
String s1="10";
String s2="20";
String temp;
System.out.println(s1);
System.out.println(s2);
temp=Integer.toString(Integer.parseInt(s1));
s1=Integer.toString(Integer.parseInt(s2));
s2=Integer.toString(Integer.parseInt(temp));
System.out.println(s1);
System.out.println(s2);
}
}
//here is also another answer:
class SwapDemo{
static int a=1, b=2 ;
public static void main(String [] args){
Swap swp = new Swap();
swp.swaps(x,y);
System.out.println( " a (was 1)now is " + a + " b (was 2) now is " + b);
}
}
class Swap{
void swaps(int c, int d){
SwapDemo f = new SwapDemo();
f.a = c;
f.a = d;
}
}
class Swap2Values{
public static void main(String[] args){
int a = 20, b = 10;
//before swaping
System.out.print("Before Swapping the values of a and b are: a = "+a+", b = "+b);
//swapping
a = a + b;
b = a - b;
a = a - b;
//after swapping
System.out.print("After Swapping the values of a and b are: a = "+a+", b = "+b);
}
}

Categories