Four values to be non zero and non negative - java

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

Related

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;
}

How to define 00-90 when I have charAt each of it

What I need to do is write a program that makes the first character (which is charAt(0) )and the second character (which is charAt(1) ) to become a value that not exceeding 90 which is (0 ~ 90) , but I also have to define them as an independent digit , because my program will make it to invalid if it is other than a digit.
So for an example it will become invalid if I type in 91
and it will valid if I type in number between 0~90
but I have no idea how to do this...
if(Character.isDigit(loop1.charAt(0))&&
Character.isDigit(loop1.charAt(1)))
I have tried this ,but not working
if(Character.isDigit(loop1.charAt(0)) &&
Character.isDigit(loop1.charAt(1)) &&
((loop1 >= 0)&&(loop1 <= 90)))
also this one but this is not working( I have no idea what I'm doing)
if(Character.isDigit(loop1.charAt(0)) &&
(((int)loop1.charAt(0)) >= 0) && <=9
Character.isDigit(loop1.charAt(1)) &&
((int)loop1.charAt(1)) <= 9)
Please help me... thanks a million !
Assuming I understand your question, parse loop1 and test the values using a simple if check, like
int t = Integer.parseInt(loop1);
if (t < 0 || t > 90) {
System.out.println("Value outside accepted range.");
} else {
System.out.println("Value valid.");
}
If I am getting this right you want to convert the first two characters of a string into a number and check is that number bigger than 90. Also you want the digits to be stored in different variables(?). If so this code should do it:
int digit1 = loop1.charAt(0) - '0';
int digit2 = loop1.charAt(1) - '0';
int number = digit1 * 10 + digit2;
if ( number <= 90 && number >= 0 )
System.out.println("Input is good");
else
System.out.println("Input is bad");

Triple Conditioned Do-While Loop With Multiple Logical Operators

I'm unable to get the do-while loop below work in Java. Thanks for your help.
do{
//User enters a value for x
//User enters a value for y
}while(x==-1 && y==-1 || x==5 || y==10);
What I'm trying to do is simply:
a) If x and y BOTH are -1 then terminate the loop
b) If x is 5 OR y is 10 then terminate the loop
You took the problem on the wrong side. There your loop will continue where you want to stop.
You should simply do the following and reverse the condition
do {
} while (!(x == -1 && y == -1 || x == 5 || y == 10));
Demo
public static void main (String[] args) {
System.out.println(conditionTesting(0, -1)); // true
System.out.println(conditionTesting(-1, -1)); // false
System.out.println(conditionTesting(5, -1)); // false
System.out.println(conditionTesting(-1, 10)); // false
System.out.println(conditionTesting(6, 9)); // true
}
public static boolean conditionTesting(int x, int y) {
return !(x == -1 && y == -1 || x == 5 || y == 10);
}
DeMorgan
If you want to go and represent it using DeMorgan's Law, you can do it using the following steps
¬((P ∧ Q) ∨ R ∨ S)
≡¬(P ∧ Q) ∧ ¬R ∧ ¬S
≡(¬P ∨ ¬Q) ∧ ¬R ∧ ¬S
So your final translation would be
(x != -1 || y != -1) && x != 5 && y != 10
Ideone Demo

How to check values in a string?

So i have a string in military time format : "1532" corresponding to 3:32pm.
I'm trying to write a method to check if each digit in time string is an appropriate digit. So the first element cannot be greater than 2 or equal to 0, and so forth. Currently, my code doesn't run past the second log statement and I'm hoping you guys could help!
cheers!
String mOpen = "1532";
Log.d("hoursTesting","pass1, length is > 2");
if(mOpen.getText().length() == 4)
{
Log.d("hoursTesting","pass2, length is == 4");
char[] tempString = mOpen.getText().toString().toCharArray();
if(tempString[0] != 0 && tempString[0] < 3)
{
Log.d("hoursTesting","pass3, first index is != 0 and < 3");
if(tempString[0] == 1)
{
Log.d("hoursTesting","pass4, first index is 1");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass5, third index is <= 5, success!");
}
}
else //tempString[0] is equal to 2
{
Log.d("hoursTesting","pass4, first index is 2");
if(tempString[1] < 4)
{
Log.d("hoursTesting","pass5, second index is <3");
if(tempString[2] <= 5)
{
Log.d("hoursTesting","pass6, third index is <= 5, success!");
}
}
}
}
}
tempString contains characters, not numbers.
i.e. '0' not 0 etc.
Easiest fix is to compare characters e.g. tempString[0] == '1' Alternatively, you can do something like int digit1 = tempString[0] - '0'; - but that kind of assumes you already know you just have digits in the string.
Note that cos of those clever ASCII guys and their tricky character set '0' < '1' < '2' etc, so you can still say if (str[0] < '2') etc. You just need to be a bit careful that you are only dealing with digits.
Personally I'd convert the first 2 chars to a number and the second 2 chars to a number and then just check 0 <= number1 <= 23 and 0 <= number2 <= 59.
You are comparing char with int here:
if(tempString[0] != 0 && tempString[0] < 3)
It should work like this:
if(tempString[0] != '0' && tempString[0] < '3')
I would substring the hours and minutes components and then check to see if each one be in range:
public boolean isTimeValid(String mOpen) {
int hours = Integer.parseInt(mOpen.substring(0, 2));
int minutes = Integer.parseInt(mOpen.substring(2));
if ((hours >= 0 && hours <= 24) && (minutes >= 0 && minutes <= 59)) {
return true;
}
else {
return false;
}
}

Enter an integer that is negative and even or positive and odd

I am creating a program that asks the user for several integers and one of the statements ask the user "Enter an integer that is negative and even or positive and odd". How exactly would I go about setting up such a question? I have this so far. I have no idea how exactly I should do this, as my instructions are pretty confusing. This is what the question is for my problem:
4.
Ask the user for an integer that is either negative and even or positive
and odd. Use an if statement and compound conditional.
import java.util.Scanner;
public class ExerciseFour
{
public static void main ( String[] argsv )
{
int choice;
int choiceTwo;
int choiceThree;
Scanner input = new Scanner(System.in);
System.out.println( "Enter a number between 0 and 10" );
choice = input.nextInt();
if ( choice > 0 && choice < 10 )
{ System.out.println( "Valid number" );
}
else
{ System.out.println( "Invalid number" );
return;
}
System.out.println( "Enter a number divisible by 2 or 3?" );
choiceTwo = input.nextInt();
if ( choiceTwo % 2 == 0 && choiceTwo % 3 == 0 )
{ System.out.println( "Valid number" );
}
else
{ System.out.println( "Number not divisible by 2 or 3" );
return;
}
System.out.println( "Enter an integer that is negative and even or positive and odd (Ex. -2 or 7 )" );
choiceThree = input.nextInt();
if ( choiceThree )
{
}
else
{
}
((choiceThree > 0) && (choiceThree % 2 == 1)) || ((choiceThree < 0) && (choiceThree % 2 == 0))
The above is the compound condition you're looking for, which means:
(
(choiceThree > 0) //positive number / greater than zero
&& // AND
(choiceThree % 2 == 1) //odd number: (an odd number divided by two has a remainder of 1)
)
|| // OR
(
(choiceThree < 0) //negative number / less than zero
&&
(choiceThree % 2 == 0) //even number (an even number divided by two has a remainder of 0)
)
EDIT: % is the modulo operator.
The result of a % b is the remainder of the integer division a / b.
The key is to use The modulo operator. An even number is divisible by 2 with no remainder. So:
if (choiceThree < 0) {
if (choiceThree % 2 == 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
} else {
if (choiceThree % 2 != 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
}
This is a bit cumbersome, of course. A more elegant way to express this boolean logic would be by using the exclusive or (xor) operator. This operator returns true if one and only one of its operands evaluate to true:
if (choiceThree > 0 ^ choiceThree % 2 == 0) {
System.out.println ("Valid");
} else {
System.out.println ("Invalid");
}
I think there is a mistake in the second question
choiceTwo % 2 == 0 && choiceTwo % 3 == 0
you may want to write || instead of && becouse you sad devisible to 2 OR 3 ;-)
For your other problem: You have two boolean expressens wich may be true:
Ask the user for an integer that is either negative and even
(choiceThree < 0 && choiceThree % 2 == 0)
or positive and odd.
(choiceThree > 0 && choiceThree % 2 == 1)
Use an if statement and compound conditional.
So just combine these to statements with a logical OR (||)
Create a method that returns true if it's one of those scenarios:
public boolean isCorrectInteger(int number){
if ((number < 0) && (number % 2 == 0)) { //negative and even
return true;
} else if((number < 0) && (number % 2 == 1)) { // positive and odd
return true;
} else { // other cases
return false;
}
}
This can be written in a one bigger condition, I've just split it into two for the sake of a simple example.
Also take into consideration that zero is currently assigned neither to positive nor negative - you can change this as you please by using the <= or >= operators.
Try this:
System.out.println( "Enter an integer that is negative and even or positive and odd (Ex. -2 or 7 )" );
choiceThree = input.nextInt();
if ( (choiceThree>0 && choiceThree%2==1) || (choiceThree<0 && choiceThree%2==0) )
{
System.out.println("Correct");
}
else
{
System.out.printlnt("ERROR");
}

Categories

Resources