Two if statements, only one works - java

I have two if statements in my code, but when both are true, it only only makes the second if. How should I write it?
String s1 = editTextl.getText().toString();
double d = 0;
if (s1.contains("H")) {
d = + H; //H is double with value of 1
}
if (s1.contains("O")) {
d = + O; //O is double with value of 16
}
TextView.setText(" " + getString(R.string.vysledek) + " " + d);
When I type HO in EditText, TextView should return value of 17, but it returns only 16. Why?

You need to write it as follows, replacing = + with +=:
if (s1.contains("H")) {
d += H;
}
if (s1.contains("O")) {
d += O;
}
+= is a so-called compound assignment operator. It adds the right operand to the left operand.
The inverse, =+, just assigns the right operand to the left operand and is equivalent to a simple assignment using =. The unary + operator is ignored.

Replace = + with +=.
= is an assignment operator, + is an unary plus operator that basically does nothing. So you're assigning a new value to the variable.
+= is "add to the current value of left hand side".

double d = 0;
if (s1.contains("H")) {
d += 1; // H is double with value of 1
}
if (s1.contains("O")) {
d += 16; // O is double with value of 16
}

Change the = + assignments to += assignments - d = + H is really just interpreted by the compiler as d = +H. You're not actually adding H to d, you're just setting d = H.

Replace d = + H with d += H and d = + O with d += O

Related

Calculating modulo inverse in java

I was trying to figure out a way to calculate modulo inverse using java so I wrote this function to do it:
public static int privatekey(int primeprod, int e, int lambda)
{
Random random = new Random();
float d = 0;
//extended euler's theorem is
//d = (1 + x*lambda) / e
//d is smaller than primeprod
while(true)
{
int d = random.nextInt(200) + 1;
System.out.println("seed: "+x);
var = (1 + (x*lambda)) / e;
System.out.println("var: "+d);
if(isInteger(d) && d < primeprod)
{
break;
}
}
int finalvar = (int)d;
return finalvar;
}
I felt that it was going wrong so I reversed euclidean theorem extension I used above as follows
1 + x.lambda
------------- = d (this one is the equation to find out d when x is any integer)
e
de = 1 + x.lambda
de - 1 = x.lambda
de - 1
------- = x (this one is to check whether the value obtained by the above equation is true or not by checking if x is the same value we had chosen for our calculation in the first place)
lambda
After doing this check I found that the value of x I obtained in the reversed equation I had solved to check for mistakes is not equal but approximate to the original random value which I had generated.
For example taking these values:
e = 327
lambda = 484
x = 76
We get d as 112.0
later We reverse The equation to find the value of x to confirm
we get:
x = 75.667355372 (Which is approximate to the original value)
I wasn't able to figure out where it was going wrong.
To look at the full program please visit this link.
Please tell me If I have done something wrong here.
Thank You in advance!
Alright I got an answer to this problem.
The Issue was I was performing arithmetic operations on integer so the value I got as result was an integer.
Instead of using integer I later used Double to do the same operation and I resolved the issue.
public static int privatekey(Double primeprod, Double e, Double lambda)
{
Random random = new Random();
float d = 0;
//extended euler's theorem is
//d = (1 + x*lambda) / e
//d is smaller than primeprod
while(true)
{
int d = random.nextInt(200) + 1;
System.out.println("seed: "+x);
var = (1 + (x*lambda)) / e;
System.out.println("var: "+d);
if(isInteger(d) && d < primeprod)
{
break;
}
}
int finalvar = (int)d;
return finalvar;
}
This resolved the issue.

difference between + and += in java? [duplicate]

This question already has answers here:
Why don't Java's +=, -=, *=, /= compound assignment operators require casting?
(11 answers)
Closed 7 years ago.
Could explain me why there is a difference when I want to sum some numbers?
int a = 4;
int b = 6;
int e = 10;
int wynik1 = a += b += e; //so it is 20.
System.out.println(wynik1);
int wynik2 = a + b + e;
System.out.println(wynik2); // so it is 46....
Should I just use always += instead of +?
I'm confused because when I was learning, for example, loops, I was using for (int p = 20; p<40; p=p+ 5) and it was working fine.
Why is it 46?
In most cases (exception) a += b as equivalent of a = a + b
So
int wynik1 = a += b += e; //so it is 20.
is same as
int wynik1 = (a = a + (b = b + e)); // so it is 20.
which means that
first b = b + e will be executed making b 6 + 10 = 16
then since b is 16 a will be assigned with result of 4 + 16 = 20
which finally will be assigned to wynik1.
So after that line (a = a + (b = b + e)) (or in your case a += b += e;) our variables will hold these values:
a = 20
b = 16
e = 10 (e didn't change since there was no e=.. in our code)
This should explain why
int wynik2 = a + b + e; //20 + 16 + 10
is 46.
+= is way different from +.
a+b means add a and b and do something with the result.
a += b means add a and b and assign the result back to a.
In your example I don't think you want to have that kind of side effect in the first expression as you probably want to use the original values in the next expression.
The += operator is distinct from the + operator in that it also assigns the result back to the variable.
a = a + 5;
a += 5;
Are equivalent.
In your example,
int wynik1 = a += b += e;
Not only is wynik1 equal to 20, but a is now also equal to 20 and b is now 16. This is why your second line returns 46:
a + b + e
= 20 + 16 + 10
= 46
The operator += is a shortcut.
Doing: a += 1; is equivalent to a = a + 1;
So, when you do: int wynik1 = a += b += e;
is reality you are doing:
int wynik1 = (a = a + (b = b + e));
+ just adds numeric values
+= adds the value on the right to the variable on the left part
Examples:
int a=3;
int b=4;
int c = a+b; // result c==7
c += 1; // result c==8
You can also use any other operator, like - * /
int d = 4;
d -= 3; // result d=1
int e=13;
int f *=3; // result f=39
As for the line:
int wynik1 = a += b += e;
b will be added with 10,
a with b, which is now 16, so the result is 20
The difference with a simple + is that the value of b is changed as well.
You could rewrite this to:
b = b + e; //results in b equals16
a = a + b; //results in a equals 20
First, note that
a += b;
is equivalent to
a = a + b;
The order of operations for assignment in Java is right to left. So,
a += b += e;
is
b = b + e; //16
a = a + b; //20
wynik1 = a; //20
Hence
wynik2 = a + b + e; //46

Need Help Finding the intersection of two equations in Java

I saw someone else posted this problem but didn't word it properly so he didn't end up receiving any help, so I figured I would try and be more direct.
Here is the problem proposed to us :
// Write and submit your code in a file called Intersect.java. Use the IO module to read inputs. Use System.out.println() to print your answer.
Write a program that calculates the intersection between 2 equations:
a degree-2 (quadratic) polynomial i.e.
y = dx^2 + fx + g
where d, f, and g are constants
and a degree-1 (linear) equation i.e.
y = mx + b
where m is the slope and b is a constant
The above is just text, not code that could appear in a Java program.
Ask the user for the constant values in each equation. Output the intersection(s) as ordered pair(s) (x,y), or "none" if none exists. Below is an example run.
java Intersect
Enter the constant d:
5
Enter the constant f:
-3
Enter the constant g:
2
Enter the constant m:
1
Enter the constant b:
3
The intersection(s) is/are:
(1,4)
(-0.20,2.8)
//
The main problem is essentially asking us to write a code that asks the user to imput the individual constants and the slope of the two equations, one being a quadratic polynomial and the other being a linear equation in point-slope.
I understand that we have to use the quadratic equation in the code, however I have no idea how to actually code this in.
Once we have had the user imput the constants, in this case 5 (d,f,g,m,b; with m being slope) we need to have the code run the calculations to imput those constants into the above example ( y = dx^2 + fx + g | y = mx + b) and return either "none" if there is no intersection, or if it does intersect, the ordered pair at which it does intersect (x,y).
I know already that if 0 is entered as the constants it returns (NaN,NaN) which I also know needs to be re-written to None.
so far I only have the following:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
If anyone can shed some light on this that would be fantastic, thanks!
EDIT1 :
So far i've changed the code to the following, however, I still don't know how to get it to return to me an answer:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
int A = d;
int B = f - m;
int C = g - b;
double x1 = - B + Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double x2 = - B - Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double y1 = m * x1 + b;
double y2 = m * x1 + b;
}
Also, eclipse is telling me that x2,y1, and y2 aren't used at all.
I know I need to use System.out.println() however I don't understand what I can put there to make the answer an ordered pair. Also, I tried setting an If statement to have the answer return None instead of NaN however it instead returns, NaN None.
There are a lot of special cases you have to take into account.
I hope I've got them all right.
So after the initialization of the values you can put this:
// calculating some useful values.
double t = -(f - m) / (2.0 * d);
double u = t * t - (g - b) / (double) d;
// the first polynomial is linear, so both terms are.
if (d == 0) {
// both linear functions have the same slope.
if (f == m) {
// both functions are shifted the same amount along the y-Axis.
if (g == b)
// the functions lie on top of each other.
System.out.println("There is an infinite amount intersections");
// the functions are shifted different amounts along the y-Axis.
else
// the lines are parallel.
System.out.println("There are no intersections");
}
// both linear functions have different slopes.
else {
// solve linear equation.
double x = (b - g) / (double) (f - m);
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
}
// the functions do not cross each other.
else if (u < 0)
System.out.println("There are no intersections");
// the linear function is a tangent to the quadratic function.
else if (u == 0) {
// solve equation.
double x = t;
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
// the linear function intersects the quadratic function at two points.
else {
// solve quadratic equation.
double x1 = t + Math.sqrt(u);
double x2 = t - Math.sqrt(u);
double y1 = m * x1 + b;
double y2 = m * x2 + b;
System.out.println("The intersections are: (" + x1 + "," + y1 + ") (" + x2 + "," + y2 + ")");
}
i guess....
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
A = d
B = f - m
C = g - b
x1 = - B + sqr( B^2 - 4 * A * C ) / (2 * A)
x2 = - B - sqr( B^2 - 4 * A * C ) / (2 * A)
y1 = m * x1 + b
y2 = m * x1 + b

while nested in for loop. How does the decrement operator work?

I couldn't figure out how the decrement operator (e--)
works in code below, so i wrote the other class below it
to get the same result. I want to know how the decrement operator
achieves that result in the Power class. - Newbie.
int result, e;
for(int i=0; i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i +
" power is " + result);
}
Code written to achieve same result
int result = 1;
for(int i=0; i < 10; i++) {
if (i > 0) {
result*=2;
}
System.out.println("2 to the " + i +
" power is " + result);
}
So the first example is resetting result for each iteration of the main for loop, so it needs to recalculate from scratch each time, where as the second example is keeping the previous computed value. The if in the second example is not needed is it.
The decrement operator modifies the variable on which it's called. So e-- is effectively e = e - 1 (except the overall result of the expression is different, see below).
This code:
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
starts with result = 1 and then loops for i iterations doubling the value in result. Equivalent code using for which you seem more comfortable with:
result = 1;
for (e = 0; e < i; e++) {
result *= 2;
}
There are two forms of the decrement (and increment) operator: Prefix and postfix, depending on whether the operator is before (prefix) or after (postfix) its operand. Either could be used in the code you were asking about, because the only difference is the result of the expression.
Prefix: Suppose we have x = 5. The expression --x has the value 4: First we decrement x, then we take its new value as the result of the expression.
Postfix: Suppose we had x = 5 (again). The expression x-- has the value 5, with x ending up containing 4: First we grab the current value of x as the result of the expression, then we decrement it (because the -- is after x).
int x, r;
x = 5;
r = --x; // Prefix
System.out.println("r = " + r + ", x = " + x); // "r = 4, x = 4"
x = 5;
r = x--; // Postfix
System.out.println("r = " + r + ", x = " + x); // "r = 5, x = 4"
i figure out that by placing a System.out.println(e) i could "see" the variable "e" behavior in order to make sense of the decrement.
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i=0; i < 10; i++) {
result =1 ;
e = i;
while(e > 0) {
System.out.println(e); // not part of the original program
result *= 2 ;
e--;
System.out.println(e); // not part of the original program
}
//System.out.println("2 to the " + i +
//" power is " + result);
}
This is the output:
C:\Users\enrique\Desktop\Hello.java>java Power: 1, 0, 2, 1, 1, 0, 3
e = 1(iteration 1), 2^1, e (1) decremented to 0, e = 2 (iteration 2), 2^2, e(2) decremented to 1, e = 1 re-enter The while but is ignored as 2^1 is already registered, e (1) decremented to 0, e = 3 (iteration 3), 2^3…

Fraction and If Statement not working Java [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Im working on a program I need to finish tonight, and basically it does a cheep version of factoring...
The problem is, that its not giving me numbers, but NaN.
Heres my code:
Class 1(Part that deals with this program):
System.out.println("--------------------------------------------------");
System.out.println(" ~Factoring~");
System.out.println("--------------------------------------------------");
System.out.println("in a polynomial, there are 3 important numbers used");
System.out.println("to figure out x. they are a, b, and c, shown below.\n");
System.out.println("\t\t1x^2 +2x -3");
System.out.println("\t\t^ ^ ^");
System.out.println("\t\ta b c");
System.out.print("\nPlease type a, b, and c here[a b c]: ");
int a = input.nextInt();
int b = input.nextInt();
int c = input.nextInt();
mathey factor = new mathey(a,b,c, chooser);
System.out.print(factor.solvefact());
Class 2:
public class mathey
{
double a,b,c;
double solution1;
double solution2;
double discriminant;
double x1 = 0;
double x2 = 0;
public mathey(int aN, int bN, int cN)
{
a = aN;
b = bN;
c = cN;
discriminant = (b*b)-4*a*c;
solvea();
solveb();
}
public String solvea()
{
solution1 = (-1*b + Math.sqrt(discriminant))/(2*a);
x1 = solution1;
if(discriminant > 0)
{
return"x = " + solution1;
}
else if(discriminant == 0)
{
return "x = " + solution1;
}
else
{
double root1complex = -b/(2*a);
double root1complex2 = Math.sqrt(-discriminant)/(2*a);
return root1complex + " + " + root1complex2 + " i ";
}
}
public String solveb()
{
solution2 = (-1*b - Math.sqrt(discriminant))/(2*a);
x2 = solution2;
if(discriminant > 0)
{
return"x = " + solution2;
}
else if(discriminant == 0)
{
return"x = " + solution2;
}
else
{
double root1complex = -b/(2*a);
double root1complex2 = Math.sqrt(-discriminant)/(2*a);
return root1complex + " - " + root1complex2 + " i ";
}
}
public mathey(int aFact, int bFact ,int cFact, int chooser)
{
a = aFact; b = bFact; c = cFact;
discriminant = (b*b)-4*a*c;
solvea();
solveb();
solvefact();
}
public String solvefact()
{
String Answer = "";
if((int)solution1 == solution1)
{
int wholeNum = (int)solution1/1;
double numerator = (solution1%1) * 10;
int denominator = 10;
while(numerator > denominator) {
denominator = denominator * 10;
}
Answer+="("+denominator+"x + "+((denominator * wholeNum) + numerator)+")";
}
else
{
Answer +="( x + " +(solution1*-1) +")";
}
if((int)solution2 == solution2)
{
int wholeNum = (int)solution2/1;
double numerator = (solution2%1) * 10;
int denominator = 10;
while(numerator > denominator) {
denominator = denominator * 10;
}
Answer+="("+denominator+"x + "+((denominator * wholeNum) + numerator)+")";
}
else
{
Answer +="( x + " +(solution2*-1) +")";
}
return Answer;
}
Heres the output:
Choose a Way to Solve
1. Quadratic Formula
2. Factoring
Which Method? [1/2]: 2
--------------------------------------------------
~Factoring~
--------------------------------------------------
in a polynomial, there are 3 important numbers used
to figure out x. they are a, b, and c, shown below.
1x^2 +2x -3
^ ^ ^
a b c
Please type a, b, and c here[a b c]: 1 2 -3
(10x + 10.0)(10x + -30.0)
How Do I fix this, so I get the Output I should get? (x + 3.0)(x-1.0)
In your 4-param constructor Mathey() (which is the constructor you are calling) you are redeclaring the variables a, b, c and assigning the values passed in to them, masking the instance variables which remain equal to 0 (the default). These local variables are only in scope in the constructor. In solveA() and solveB(), a, b, c again refer to the instance variables (which are all 0), so you're dividing by 2*a = 0, which makes solution1 and solution2 equal to NaN.
Change the line in the second constructor (if you continue to use it) from
double a = aN, b = bN, c = cN;
to
a = aN, b = bN, c = cN;
to solve the masking issue. You most likely want the instance variables to be doubles rather than ints, though, so change
int a;int b;int c;
to
double a, b, c;
(you can do multiple declarations of the same type like this).
I don't know why you have two Mathey constructors, so either scrap the second one (what is chooser?) and just use the first, or make sure the second one also assigns a value to determinant.
This should be a start, anyway.
You should check if you have the possibility your code by unit testing the functions.
For instance I noticed you used a {%} operator with a double number. That operator works with integers, and may drag the NaN result until the end.
You are also declaring variables in mathey() and then trying to use them in solvea() solveb() where they don't exist.

Categories

Resources