Write a Processing method to return one of three strings, depending on the value of the parameter x. If x is even, the method should return “Even”. If x is divisible by three, the method should return “By three”. If x is neither even nor divisible by three, the method should return “Just odd”.
The signature for your method should be String evenOdd(int x)
The issue with your code, which you have left in the comments, is that they are asking for the number to be divisible by three, meaning a remainder of 0. Your code is trying to find a remainder of 3.
so, rather than writing if (x % 3 == 3), say if (x % 3 == 0).
Basically your full code would look as follows:
string evenOdd(int x)
{
string theResponse = "";
if (x % 2 == 0) // if x is divisible by 2 with no remainders
{
theResponse = "Even!";
}
else if (x % 3 == 0) // if x is divisible by 3 with no remainders
{
theResponse = "By three!";
}
else
{
theResponse = "Odd";
}
return theResponse;
}
String evenOdd(int x)
{
if (x%2 == 0) //number is even when it is divisible by 2
return "Even";
else if(x%3 == 0) //if remainder is 0 then it is divisible by three
return "By three";
else
return "Just Odd";
}
Related
Currently doing a challenge called number to words, I have created 2 methods, one which
deals with comparing values individually so that it can print out it's string value(method called numberToWord), another method called reverse which basically re-orders the values so that it is printed in a correct sequence, for example:s
Step One 567 --> Step 2, it will be converted into 765 --> Step 3, reverse method will then convert it back to 5,6,7 individually so that it can compare the values with the if statements. However, i have tried so many things to getting this to work, i managed to make it to step 3 but when i try to return the value it gives me 3 random values before it converts e.g = 7,6,7...5,6,7, i am unable to figure out how to remove the first 3 values and return just the last three values so that it can be compared in the numberToWords method.
package com.company;
public class Main {
public static void main(String[] args) {
numberToWords(567);
}
public static void numberToWords(int number) {
int lastDigit = 0;
int digit = number;
int reverseDigit = 0;
if (number < 0) {
System.out.println("Invalid Value");
}
for (int i = 0; i < digit; i++) {
//so we are taking the last digit from 567 per iteration
lastDigit = digit % 10;
//we are then dividing the digit by 10 each time so we can get another last digit
digit /= 10;
//i will now try to essentially get down to the final number which will be flipped
reverseDigit = (reverseDigit * 10) + lastDigit;
//checking values
System.out.println(reverse(reverseDigit));
// if (reverse(reverseDigit)== 0) {
// System.out.println("Zero");
// } else if (reverse(reverseDigit) == 1) {
// System.out.println("One");
// }else if (reverse(reverseDigit) == 2) {
// System.out.println("Two");
// }else if (reverse(reverseDigit) == 3) {
// System.out.println("Three");
// }else if (reverse(reverseDigit) == 4) {
// System.out.println("Four");
// }else if (reverse(reverseDigit) == 5) {
// System.out.println("Five");
// }else if (reverse(reverseDigit) == 6) {
// System.out.println("Six");
// }else if (reverse(reverseDigit) == 7) {
// System.out.println("Seven");
// }else if (reverse(reverseDigit) == 8) {
// System.out.println("Eight");
// }else if (reverse(reverseDigit) == 9) {
// System.out.println("Nine ");
// }
if (lastDigit == 0) {
System.out.println("Zero");
} else if (lastDigit == 1) {
System.out.println("One");
} else if (lastDigit == 2) {
System.out.println("Two");
} else if (lastDigit == 3) {
System.out.println("Three");
} else if (lastDigit == 4) {
System.out.println("Four");
} else if (lastDigit == 5) {
System.out.println("Five");
} else if (lastDigit == 6) {
System.out.println("Six");
} else if (lastDigit == 7) {
System.out.println("Seven");
} else if (lastDigit == 8) {
System.out.println("Eight");
} else if (lastDigit == 9) {
System.out.println("Nine");
}
}
}
public static int reverse (int a){
int lastDigit = 0;
for (int i =0; i < a; i++) {
lastDigit = a % 10;
a /= 10;
//testing values here
//System.out.println(lastDigit);
//sout in loop gives us 567
}
return lastDigit;
}
}
If I understand what you need correctly, you don't need that much code. Just print the reminder of division by 10 and then divide by ten for then next iteration until you get zero.
enum Numbers {
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine;
}
private static void process(int number) {
do {
final int digit = number % 10;
System.out.println(Numbers.values()[digit]);
number /= 10;
} while (number > 0);
}
First use an enum since you can use it like an array but easier to declare. Then with the number you get, first get the reminder over ten. For any integer expressed as decimal the reminder over ten is the last digit. Since you have to print the last digit in the first place, just print it. Then replace number with number divided by ten. That will discard the last digit (the one just printed out) because this is an integer division. I mean, 1234 over 10 is 123.4 but because these are integer it gets truncated to 123. So now loop and the last digit will be printed again (but now it will be the first to the left due to the division). At some point, after printing the first digit of the original number you will have a one digit integer (i.e. 7) divided by ten which results in zero (because it would be 0.7 but it's an integer division).
You need to add some preconditions like the negatives.
I think you have the right idea of doing remainder division for numberToWords() and reverse().
But I think you're condition for exiting the for loop is wrong
for (int i = 0; i < digit; i++)
It will exit before you get all the digits. You want to loop until digit is 0, since you want to remainder divide UNTIL there's no more to divide ( meaning digit is 0).
so
for(int i = 0; digit != 0; i++){
...
}
while loop might be better than a for a loop since you're not using i anyways.
while(digit != 0){
...
}
It also depends on which IDE you're using but IntelliJ and eclipse can do a line by line debug so you see which line is causing issues.
public int bunnyEars(int n) {
if (n < 0) {
throw new IllegalArgumentException();
}
if (n == 0) {
return n;
}
if (n % 2 == 1)
return 2 + bunnyEars(n - 1);
return 3 + bunnyEars(n - 1);
}
can someone explain how bunnyEars(2) = 5
and also how it works?
If the number n is less than 0, then an IllegalArgumentException is thrown, as evidenced by:
if (n < 0) {
throw new IllegalArgumentException();
}
So, we know n is always supposed to be 0 or greater. We also know that the method is supposed to return when n is equal to 0, as evidenced by:
if (n == 0) {
return n;
}
So, presumably, the method public int bunnyEars(int n) will take a number equal to or greater than zero, and will start adding integers until the n is zero.
We see two different possible scenarios to take n's greater than zero and do something with them:
if (n % 2 ==1)
return 2 + bunnyEars(n-1);
return 3 + bunnyEars(n -1); //else
What is happening here is if the n % 2 is equal to one (meaning that the number is odd, since every odd integer divided by two has a remainder of one), then the method is recursively called with the current n minus 1, and the final integer to return is incremented by two.
If the number is not odd (and is thus even), then the same thing is happening, but with the final integer to return incremented by 3.
So in your example of bunnyEars(2), we see that the n of 2 is both positive and greater than zero, so no error is thrown and the method does not return without recursion. Since 2 is an even number (2 % 2 is 0), the second return is used. This means that 3 + bunnyEars(1) is called.
Since 1 is also greater than 0, we go to the recursive methods again. Since 1 is an odd number (1 % 2 is 1), the first recursive return is called. This means we call 2 + bunnyEars(0).
Now, since n is 0, the return n from the if-statement is used:
if (n == 0) {
return n;
}
On the first round we had the final integer to return incremented by 3, and on the second time it was incremented by 2, for a total of 5. So the result is five.
From your comments, I understand that you already know the meaning of a recursive call. In order to make it clear how it works, you can trace the calls in some way. Given below is an example of one of the ways:
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println(bunnyEars(2));
}
static int bunnyEars(int n) {
if (n < 0) {
throw new IllegalArgumentException();
}
if (n == 0) {
System.out.println(n);
return n;
}
if (n % 2 == 1) {
System.out.print("2 + bunnyEars(" + n + "-1) -> ");
return 2 + bunnyEars(n - 1);
}
System.out.print("3 + bunnyEars(" + n + "-1) -> ");
return 3 + bunnyEars(n - 1);
}
}
Output:
3 + bunnyEars(2-1) -> 2 + bunnyEars(1-1) -> 0
5
As you can see, 3 + 2 + 0 = 5 is what you get as the answer.
I hope, it helps. Feel free to comment in case of any doubt.
I am trying to solve this : Given an integer, return 1 if the number is between -5 and 5 exclusive and/or if it is an odd integer. If neither properties apply, return 0.
Here is what I have tried:
int rangeOrOdd(int val) {
if (val < 5)
return 1;
else if (val > 5)
return 1;
else if ((val%2)!=0)
return 0;
else
return 0;
}
The problem is that you are checking the different conditions individually. For instance, as soon as your number is smaller than 5, you return 1, which is wrong, because you would then return 1 for numbers like -1000.
Also, you are returning 0 for an odd number. You were supposed to return 1 in that case.
You have to combine your conditions using ANDs (&&) and ORs (||).
Here is a one liner that combines the different conditions correctly:
return ((val < 5 && val > -5) || val % 2 == 1) ? 1 : 0;
And if you don't like it in one line, you can always split it like this (but it's the same thing):
if ((val < 5 && val > -5) || val % 2 == 1) {
return 1;
} else {
return 0;
}
I have this exercise that asks me to create a program to count the odd digits of a number, so if the number is 12345 it will count to 3, because of 1, 3 and 5. I started creating a recursive method, my very first one, with a ramified if-else. The point of using it was to see if (inputNumber % 2 == '0'). If yes, the last digit of the number would be a 0, 2, 4, 6 or 8, because only those digits give 0 if moduled by 2, so oddDigitsCounter wouldn't grow. Else, if (inputNumber % 2 == '1'), the last digit of the number would be 1, 3, 5, 7 or 9. oddDigitCounter++;, so. To check digit by digit I tried to divide the number by ten because it is a int variable, so it doesn't saves any digit after the floating point.
This is the method since now:
public static int oddDigitCounter (int number) {
int oddCount, moduledNumber, dividedNumber, absoluteInput;
oddCount = 0;
absoluteInput = Math.abs(number);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == '0') {
oddCount = oddCount; }
else if (moduledNumber == '0') {
oddCount = oddCount;
oddDigitCounter(dividedNumber); }
else // (number % 2 != 0)
oddCount++;
oddDigitCounter(dividedNumber); }
return oddCount;
Why it gives me an infinite recursion? What's wrong? Why? Any other way to solve this? Any idea for improving my program?
You don't use the result of the recursive call. You also compared a integer to the character '0', which is not the same as comparing to 0.
public static int oddDigitCounter (int number)
{
int moduledNumber, dividedNumber, absoluteInput;
inputAssoluto = Math.abs(numero);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == 0) {
return 0;
}
else if (moduledNumber == 0) {
return oddDigitCounter(dividedNumber);
}
else {
return 1 + oddDigitCounter(dividedNumber);
}
}
Declare odd counter outside of recursion and you should get results :
static int oddCounts;
public static int oddDigitCounter(int number) {
int moduledNumber, dividedNumber, absoluteInput = 0;
absoluteInput = Math.abs(number);
moduledNumber = absoluteInput % 2;
dividedNumber = absoluteInput / 10;
if (absoluteInput == 0) {
return 0;
} else if (moduledNumber == 0) {
return oddDigitCounter(dividedNumber);
} else {
oddCounts++;
return 1 + oddDigitCounter(dividedNumber);
}
}
As mentioned in the comments, you should compare to 0 and not to '0'. The latter will be interpreted as 48, the ASCII character for the numeral zero.
Furthermore, absoluteInput is never assigned to and will always have its initial value 0. Where does inputAssoluto come from?
Wouldn't you want to list your numbers and then check each one as a single int again, meaning you can check digit by digit and don't have to divide the number by ten.
a very short solution will then suffice: (if your passing the number as a string the LINQ one-liner can give you what you want).
static int OddDigitCounter(int numbers)
{
var c = numbers.ToString();
var oddcount = c.Count(no => int.Parse(no.ToString()) % 2 != 0); //<--one liner
return oddcount;
}
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;
}