JAVA checking two numbers digit are the same - java

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

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

reading from a file wont read the first value Java

So i Have this code going on, I need it to open a file, and scan the two integers in the file, then I need it to store the two numbers. The numbers are restricted to between 1 and 10 for the first number and between 1 and 39 for the second number. I have a valueCounter to make sure that the correct number gets stored in the correct variable. For some reason, the code always returns
"Your Initial Fib is out of range, eneter # between 1-10"
Which would be appropriate if the first number was greater than 10 or less than 1, but regardless of what i change the first number to, the code returns the same line. The only time it wont return that line is when i change the 2nd number to to be between 1 and 10. So I can conclude that the code is skipping the first number, but i cant figure out why. Any being of higher intelligence that can help?
private static File inFile = null;
private static PrintWriter outFile = null;
private static int startValue;
private static int lengthValue;
public static void main(String[] args) throws IOException
{
inFile = new File( inFileName);
Scanner in = new Scanner (inFile);
outFile = new PrintWriter (outFileName);
int valueCounter = 1;
while (in.hasNextInt())
{
int value = in.nextInt();
if ( value <= 39 && value >= 1 && valueCounter == 2)
{
lengthValue = value;
valueCounter ++;
}
if ( value > 39 || value < 1 && valueCounter == 2)
{
System.out.println("You are asking for too many Fib, eneter # between 1-39");
in.close();
System.exit(1);
}
if ( value <= 10 && value >= 1 && valueCounter == 1)
{
startValue = value;
valueCounter ++;
}
if ( value > 10 || value < 1 && valueCounter == 1)
{
System.out.println("Your Initial Fib is out of range, eneter # between 1-10");
in.close();
System.exit(1);
}
}
}
It is because of operator precedence, the && is evaluated before the ||. This makes the following expression
if ( value > 10 || value < 1 && valueCounter == 1)
evaluated to true the second round, because first value < 1 && valuecounter == 1 is evaluated, which is false. Next, value > 10 is evaluated, which is true. Or-ing both results in true, and the body executes. Use parentheses to control the order of evaluation.
if ( value > 10 || value < 1 && valueCounter == 1)
Seems to be always true and since its a normal outer "if" at the end of code, its always being called. overthink your "if" and its appearance

Why would the method not allow inputs from 11-15?

This is code from Cracking the Coding Interview 5th Edition
I got this from
https://code.google.com/p/ctci/source/browse/trunk/Java/Introduction/CompareBinaryToHex/CompareBinaryToHex.java?spec=svn18&r=3 (didn't want to take and upload a picture of a few pages from the book)
Here's the code
public class CompareBinaryToHex {
public static int digitToValue(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return 10 + c - 'A';
} else if (c >= 'a' && c <= 'f') {
return 10 + c - 'a';
}
return -1;
}
public static int convertToBase(String number, int base) {
if (base < 2 || (base > 10 && base != 16)) return -1;
int value = 0;
for (int i = number.length() - 1; i >= 0; i--) {
int digit = digitToValue(number.charAt(i));
if (digit < 0 || digit >= base) {
return -1;
}
int exp = number.length() - 1 - i;
value += digit * Math.pow(base, exp);
}
return value;
}
public static boolean compareBinToHex(String binary, String hex) {
int n1 = convertToBase(binary, 2);
int n2 = convertToBase(hex, 16);
if (n1 < 0 || n2 < 0) {
return false;
} else {
return n1 == n2;
}
}
public static void main(String[] args) {
System.out.println(compareBinToHex("111001011", "1CB"));
}
}
Basically a method inside this class compareBinToHex, takes in String representations of a binary number and a hex number and returns whether or not they are equal or not(in decimal value). It uses the method convertToBase to convert from that base to decimal.
My question is for the convertToBase method, why are base inputs in the range 2-9 and 16 allowed, but
base inputs from 11-15 are not? (Base inputs in range 2-9 and 16 will not go in the return -1 if block) Gayle, the author later summarized that it's better to write code that is more flexible and general-purpose which I would agree with and is the reasoning behind my argument for the allowance of 11-15 base inputs. Say if you're working with base 11. I believe convertToBase should still work for this because you're counting to 'A' which should still work behind the logic(range 'A' to 'F') in digitToValue. Is there a reason why she disallowed those inputs?
Because very few people need a base (or radix) 11, 12, 13, 14 or 15 calculator. It's important to note that base 8 is octal, base 2 is binary, base 10 is decimal and base 16 is hexadecimal. I would go further and suggest you explicitly check it's one of those,
if (base != 2 && base != 8 && base != 10 && base != 16) return -1;

Detect if number is a multiple of 7 or contains the number 7

I read a book about challenges in Java, and it gives the next question:
create a function, which get a number as argument, and detect if number is a multiple of 7 or contains the number 7.
The signature is: public boolean find7(int num)
I create this function, when the number is between 0 to 99, by the next condition:
if (num mod 7 == 0 || num / 10 ==7 || num mod 10 == 7)
return true;
But what with number which is greater than 99? like 177, or 709? How can I detect it?
It's probably best to leave strings out of this:
public static boolean check(final int n) {
int m = Math.abs(n);
while (m > 0) {
if (m % 10 == 7)
return true;
m /= 10;
}
return n % 7 == 0;
}
The while-loop checks each digit and tests if it is 7; if it is, we return true and if it isn't, we continue. We reach the final return statement only if none of the digits were 7, at which point we return whether the number is a multiple of 7.
if (num % 7 ==0 || ("" + num).contains("7") ){
return true;
}
You can extend your approach to numbers above 100 like this:
public boolean find7(int num) {
// support for negative integers
num = Math.abs(num);
// check if num is a multiple of 7
if (num % 7 == 0) {
return true;
}
// check to see if num contains 7
while (num > 1) {
// if the last digit is 7, return true
if (num % 10 == 7) {
return true;
}
// truncate the last digit
num /= 10
}
// the number is not a multiple of 7 and it does not contain 7
return false;
}
You can do the following
if(Integer.toString(num).contains("7") || ...){
}
As far as checking if the number is divisible by 7, you're fine.
If you want to check if it contains the 7 digit, I think the easiest approach would be to treat the number as a String:
public boolean find7(int num) {
// check if it's a multiple of 7:
if (num % 7 == 0) {
return true;
}
// if it's not, check if it contains the character 7:
return String.valueOf(num).contains("7");
}
For detecting if number is multiple of 7:
boolean isMultiple = x % 7 == 0
For detecting digit:
Convert it to String and use String.contains()
or
Create digit List like this:
private List<Integer> getDigitList(int number){
List<Integer> list = new ArrayList<Integer>();
int leftover = number;
while (leftover != 0){
int result = leftover % 10;
leftover = (leftover - result)/10;
list.add(result)
}
assert leftover == 0;
return list;
}

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