Multiple Meaning on "if" Statement - java

I am trying to implement if slope one is positive(greater than zero) and slope1 is positive multiply by -1
'Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token ";", . expected
slope1 cannot be resolved or is not a field
at LinearSlopeFinder.main(LinearSlopeFinder.java:25)
;
i have tried using an "," instead but no dice
import java.util.Scanner;
public class LinearSlopeFinder {
public static void main(String[]args){
double x1, y1, x2, y2, n1, equation, constant = 0 ;
double slope, slope1, slopeAns;
Scanner myScanner = new Scanner(System.in);
System.out.print(" What is the first set of cordinants? example: x,y ... ");
String coordinate1 = myScanner.nextLine();
String coordinates[] = coordinate1.split(",");
x1 = Integer.parseInt(coordinates[0]);
y1 = Integer.parseInt(coordinates[1]);
System.out.print(" What is the second set of cordinants? example: x,y ... ");
String coordinate2 = myScanner.nextLine();
String coordinates1[] = coordinate2.split(",");
x2 = Integer.parseInt(coordinates1[0]);
y2 = Integer.parseInt(coordinates1[1]);
//remember it is Rise over Run Y's over X's
slope = (y1-y2);
slope1= (x1-x2);
slopeAns= slope / slope1 ;
//below is the part that is not compiling but I am trying to insert
if ( slope > 0 ; slope1 > 0 ){
slope = slope * -1;
slope1 = slope1 * -1;
}

You want to use the && operator for 'and'. I recommend you read the operators section of the Java tutorial (the rest is valuable too).

In Java you are looking for an AND operator for the if statement to combine the two Boolean results from slope > 0 and slope1 > 0 into one Boolean. The AND operator is && so try:
if(scope > 0 && scope1 > 0) {
scope *= -1;
scope1 *= -1;
}
Other Boolean logical operators are | (OR), & (AND), ^ (XOR), ! (NOT), || (short-circuit OR), && (short-circuit AND), == (EQUAL TO), != (NOT EQUAL TO), ?: (IF-THEN-ELSE).
The difference between | and || is that in Java if the first statement turns out to be true then it will not evaluate the second or more statement with || but it will with |. The same goes for && if the first statement is equal to false.

Replace ; with &&.
if( slope > 0 && slope1 > 0)

This is wrong:
if ( slope > 0 ; slope1 > 0 ){
Do you mean:
if ( slope > 0 && slope1 > 0 ){

Related

Four values to be non zero and non negative

Suppose I have four variables x, y, z, w. I want to print:
"hello all non zero values" only if all x, y, z, w are non-negative and non-zero values.
If all the values are zero, then print "hello zero".
If any of the values (one, two or three but not all of them) is zero or negative then print "illegal values".
I've written a sample solution which handles and clubs negative as well as non-negative values:
if((x&y&z&w) == 0 && !(x==y && y==z && z==w && w==0)) {
System.out.println("illegal values");
} else {
System.out.println("hello all non zero values");
}
However, I am not able to handle the negative and positive values separately. Can anyone please suggest a solution for it?
The bit-fiddling approach:
String s;
int j = w & x & y & z;
int k = w | x | y | z;
if (k == 0)
s = "hello zero";
else if (j != 0 && k > 0)
s = "hello all non-zero values";
else
s = "illegal values";
System.out.println(s);
This works because the bitwise-and is zero if any of the four values is zero, the bitwise-or is non-zero if any of the four values is non-zero; and the sign bit is set in the result (i.e., negative) if the sign bit is set in any of the four values.
(And I use the temporary 's' because why write 3 calls to the same routine)
Edited: this answer was updated after a recent edit to the question, which has clarified the criteria.
It might help to reword your question in a different but equivalent way. You are basically printing "hello zero" if all of them are zero, "hello all non zero values" if all of them are positive, and "illegal values" in all other cases.
if (x == 0 && y == 0 && z == 0 && w == 0) {
System.out.println("hello zero");
} else if (x > 0 && y > 0 && z > 0 && w > 0) {
System.out.println("hello all non zero values");
} else {
System.out.println("illegal values");
}
Something like this?
if (x > 0 && y > 0 && z > 0 && w > 0) {
System.out.println("hello all non zero values");
} else if (x == 0 && y == 0 && z == 0 && w == 0) {
System.out.println("hello zero");
} else {
System.out.println("illegal values");
}
Does this work for you?
if ((x>0)&(y>0)&(z>0)&(w>0)) {
System.out.println("hello all non zero values");
} else {
System.out.println("illegal values");
}
Edit: this doesn't fully answer the question, my apologies

JAVA checking two numbers digit are the same

hi I am trying to solve Udemy exercise:
Write a method named hasSharedDigit with two parameters of type int.
Each number should be within the range of 10 (inclusive) - 99 (inclusive). If one of the numbers is not within the range, the method should return false.
The method should return true if there is a digit that appears in both numbers, such as 2 in 12 and 23; otherwise, the method should return false.
I am keep getting true while hasSharedDigit(9,99) I cant discover why..
public class SharedDigit {
public static boolean hasSharedDigit(int number1, int number2){
if((number1 <10 || number1 >99) && (number2 <10 || number2 >99)) {
return false;
}
int numberOneFirstDigit = number1/10;
int numberTwoFirstDigit = number2/10;
int numberOneLastDigit = number1%10;
int numberTwoLastDigit = number2%10;
if(numberOneFirstDigit == numberTwoFirstDigit || numberOneFirstDigit == numberTwoLastDigit || numberOneLastDigit == numberTwoLastDigit) {
return true;
} else {
return false;
}
}
}
If one of the numbers is not within the range, the method should
return false.
Replace
if((number1 <10 || number1 >99) && (number2 <10 || number2 >99))
with
if(number1 <10 || number1 >99 || number2 <10 || number2 >99)
Apart from this, you have missed numberOneLastDigit == numberTwoFirstDigit in the combination of conditions which are supposed to compare the digits i.e. the combination should be
if(
numberOneFirstDigit == numberTwoFirstDigit ||
numberOneFirstDigit == numberTwoLastDigit ||
numberOneLastDigit == numberTwoFirstDigit ||
numberOneLastDigit == numberTwoLastDigit
)
Treating numbers as text
The other Answer and comments solved your direct problem. Just for fun, we can take an entirely different approach.
The idea here is to treat the numbers as text. In doing so, we can address each of your two business rules:
Each number should be within the range of 10 (inclusive) - 99 (inclusive).
Numbers between 10 and 99 happen to have exactly two digits. One digit or 3+ digits means out-of-range.
if there is a digit that appears in both numbers
By collecting into a Set the code point of each character in the string that is our first number, we have a distinct collection for which we can get the intersection of the same for the second number’s string. If the intersection, the resulting modified Set, has a size over 0, then we know digits are shared.
To explain the code below… The codePoints method generates an IntStream, a sequence of int numbers, one for each code point number defined in Unicode for each character in our string that represents our input integer. The boxed call converts those int primitives into Integer objects. Adding those Integer objects to a Set automatically makes them distinct, weeding out automatically any duplicate digits.
See this code run live at IdeOne.com.
private boolean twoIntsAreInRangeAndShareDigits ( int n1 , int n2 )
{
String n1String = Integer.toString( n1 );
String n2String = Integer.toString( n2 );
// Check for negative numbers, meaning out-of-range, not 10-99.
if ( n1String.concat( n2String ).contains( "-" ) ) { return false; }
// Check for exactly 2 digits, meaning within range, 10-99.
if ( ( n1String.length() == 2 ) && ( n2String.length() == 2 ) )
{ // Numbers are within range.
// Check for common digits.
Set < Integer > n1CodePoints = n1String.codePoints().boxed().collect( Collectors.toSet() );
Set < Integer > n2CodePoints = n2String.codePoints().boxed().collect( Collectors.toSet() );
n1CodePoints.retainAll( n2CodePoints );
boolean sharesDigit = ( n1CodePoints.size() > 0 );
return sharesDigit;
}
else // Else 1 or 3+ digits mean numbers are out-of-range.
{ return false; }
}
I am not arguing that this approach is better, just interesting as a different way of thinking about the problem.
You're missing a comparison here. What you have is f1 == f2 || f1 == l2 || l1 == l2 but what's missing it l1 == f2, e.g. 12 and 23 would return false with your code because
1 != 2 (f1 == f2 fails)
1 != 3 (f1 == l2 fails)
2 != 3 (l1 == l2 fails)
your code is missing the 2 == 2 (l1 == f2) so add ... || numberOneLastDigit == numberTwoFirstDigit to the comparison condition.
As the others already stated, your check is also wrong as it requires both numbers to be out of range so if just one is, it doesn't return false.
To make it easier, try to turn the condition around so that both numbers must be in range:
if(!(number1 >= 10 && number1 <=99 && number2 >= 10 && number2 <= 99)) {
return false;
}
Often it might also be easier to read and maintain the code if you'd "name" the conditions:
boolean n1InRange = number1 >= 10 && number1 <=99;
boolean n2InRange = number2 >= 10 && number2 <=99;
if( !(n1InRange && n2InRange) { ... }
//or
if( !n1InRange || !n2InRange ) { ... }
This is my Solution
public static boolean hasSharedDigit(int x, int y){
if( (x < 10 || x > 99) || (y < 10 || y > 99)){
return false;
}
int xFirst = x / 10;
int yFirst = y / 10;
int xLast = x % 10;
int yLast = y % 10;
if((xFirst == yFirst || xLast == yLast) || (xFirst == yLast || xLast == yFirst)){
return true;
} return false;
}

Hard time finding an error in my code

I have some problems with my java code here. When I try to compile I get the error:
"bad operand types for binary operator '&&'" for the if statement
which I usually get when I made an error in the boolean logic. For the past half hour I've tried to find the mistake in my code but I'm not able to find it.
Any pointers?
code below
public String toString(){
double x1 = this.ecke1.getX();
double y1 = this.ecke1.getY();
double x2 = this.ecke2.getX();
double y2 = this.ecke2.getY();
double[] Y = {y1,y2,0};
double[] X = {x1,x2,0};
for (int y = 0; y <= Utils.max(y1,y2,0); y++)
for(int x = 0; x <= Utils.max(x1,x2,0); x++)
if ( ((x=0) && (y=0) ) || ( ( (y/x) <= (Utils.min(X)/Utils.max(Y)) ) && ( (y/x) >= (Utils.min(Y)/Utils.max(X)) ) && ( (y/x) <= ((Utils.max(Y)-Utils.min(Y)) / (Utils.min(X) - Utils.max(X))) ) ) )
System.out.print("#");
else system.out.print("-");
}
Change
(x=0) && (y=0)
to
(x==0) && (y==0)
x=0 is an assignment, so it doesn't evaluate to a boolean. x==0 is a comparison, and returns a boolean.
Use double equal to sign(==) instead of single(=)
if (((x==0) && (y==0) )...)
You use single equal sign for assignment and double for comparison.
= is an assignment operator while == is a comparison operator.
So you need to use x == 0 && y == 0.

float within 3 of each other if else statement?

Is there a way in Java to make it so that if X is within 3 of Y that it will be true (need a if statement).
I tried:
import java.util.*;
import java.io.*;
public class e4 {
public static void main (String arg[]) {
if ( ( (x - 3) <= y ) || ( (x - 3) <= y) || (x >= (y -3) ) || (x >= (y -3) ))
{
System.out.println("Your are within 3 of each other!");
}
else
{
System.out.println("Your NOT within 3 of each other.");
}
} //end main
} //end class
Thanks a lot for any help!
Use something simpler:
if (Math.abs(x - y) < 3.0) {
// within 3
}
You don't need Math.abs. Do this.
if ( x >= y - 3 && x <= y + 3 )
Here's a case where Math.abs gives you a wrong answer, because the subtraction loses the small quantity from the small float. If accuracy is important to you, you should avoid using Math.abs for this reason.
Note that it's possible to concoct an example where a similar thing happens with MY solution; but there are fewer such examples, and they only happen where the "ranges" represented by x and y contain parts that differ by more than 3 and parts that differ by less than 3.
float x = - 0.2500001f;
float y = 2.75f;
System.out.println( x >= y - 3 && x <= y + 3 ); // Prints false (correct)
System.out.println( Math.abs(x-y) <= 3.0); // Prints true (wrong)

Using Boolean Algebra to determine a limit between two numbers?

I have to use only Boolean and if statements to determine if a number is between 141 and 185 and whether it is lower or higher than that number. I am stumped.
double maxHR= 220- Double.parseDouble(yearsOld); //maximum heart rate
double reserveHR= maxHR- Double.parseDouble(restingHR); //heart rate reserve
double upperEndZone= (reserveHR*.85)+Double.parseDouble(restingHR);
double lowerEndZone= (reserveHR*.50)+Double.parseDouble(restingHR);
boolean isTargetRateLow= lowerEndZone<= Double.parseDouble(restingHR) ;
Is there a way to put two operators within one boolean statement? I think that would solve my issue.
By two operators in one boolean statement do you mean :
boolean bool = a <= b && c >= d
As in the AND operator (&&)
Is this what you need?
boolean isInbetween = (x >= lowerEndZone) && (x <= upperEndZone);
Do you mean something like
// determine if x is in [a,b]
bool in_fully_closed_interval = (a <= x) && (x <= b);
// determine if x is in [a,b)
bool in_closed_left_open_right_interval = (a <= x) && (x < b);
// determine if x is in (a,b]
bool in_open_left_closed_right_interval = (a < x) && (x <= b);
// determine if x is in (a,b)
bool in_open_interval = (a < x) && (x < b);
Yes, I KNOW other people have posted this. I do it to show what I consider more readable variations.

Categories

Resources