Okay so my question is how can I display odd and even digits of a single int input not the whole input. This while using "for" or "while" loop and the % modulator. For example, the program ask a user to enter a positive integer and then it would read each digit and list even and odd digits. I was unable to find a method that reads each character except for the .charAt() but I cant make it work. This is my fail attempt. NOTE: I can't use the % modulator because idk any method to read each digit for an int. Please help, thanks.
String = userEntry
int r = userEntry.length() - 1;
System.out.print("The even numbers are ");
int c = 0; // 0 would count as even.
int size = 0;
while (size < r && c < 9)
{
if (c == userEntry.charAt(size))
{
outputFile.print(" " + userEntry.charAt(size));
System.out.print(" " + userEntry.charAt(size));
size++;
}
else
{
c+=2;
}
For that you can use the modulo operator.
public class Main {
/** http://stackoverflow.com/q/36053971/6077352 */
public static void main(String[] args) {
int input = 123456789;
while (input > 0) {
if (input % 2 == 0) {
System.out.println(input % 10 + " is even");
} else {
System.out.println(input % 10 + " is odd");
}
input = input / 10;
}
}
}
Example output:
9 is odd
8 is even
7 is odd
6 is even
5 is odd
4 is even
3 is odd
2 is even
1 is odd
An if statement would do the job of deciding whether the number is odd or even. As for the for statement, in order to run it through the whole array you would use code like this:
for(*variable* = 0; *variable* < userEntry.length; *variable*++)
{
}
The mod operator gives you the remainder of doing division on an int.
So any number mod 10 will return the last digit because the remainder of dividing a digit less than 10 is the number itself. So 30%10=0 and 32%10=2. So you can use the mod to separate the digits.
And then for each digit you want to check if if it is even or odd. even numbers are divisible by 2 so number%2 should leave no remainder.
You then have to divide your number by 10 to do the same for the tens column and then again for the hundreds column and so on. This should work for you.
while (number>0) {
if ((number%10)%2==0) {
System.out.println(number % 10 + "even");
}
else {
System.out.println(number % 10+ "odd");
}
number = number / 10;
}
Related
how do I get this loop to print all the divisors with two user inputted numbers including 1 but just print 1 and relatively prime when the two numbers have no common divisors.
System.out.println("Common divisors of " + a + " and " + b + ":");
for (int i = 1; i <= b; i++)
if (a % i == 0 && b % i == 0) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
if (i == 1)
System.out.println("Relatively Prime");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter two positive integers:");
int input1 = scan.nextInt();
int input2 = scan.nextInt();
printCommonDivisors(input1, input2);
}
}
Right now it says relatively prime after 1 even if the numbers have common divisors.
I am just trying to get it to say relatively prime when the two numbers only common divisor is 1 but also not print relatively prime after 1 when the numbers do have more common divisors. this the output right now.
Please enter two positive integers:
10
20
Common divisors of 10 and 20:
1
Relatively Prime
2
5
10
You need a boolean value to store whether you have found a greater-than-one divisor inside the loop. Instead of
if (i == 1)
System.out.println("Relatively Prime");
Check the boolean value after the loop and print "Relatively Prime" if a divisor was not found.
You have the line if (a % i == 0 && b % i == 0) { twice, you only need to have one of it, make sure to remove the closing brace for it as well.
If you want to print "relatively prime" only if there were no other divisors, you should check for other divisors first (for instance by starting with the large numbers and working your way down, rather than starting with small numbers and working your way up) and if you find one, somehow record this fact so you later know not print "relatively prime".
In code:
boolean divisorFound = false;
for (int i = b; i > 1; i--) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
divisorFound = true;
}
}
System.out.println(1);
if (!divisorFound) {
System.out.println("relatively prime");
}
Of course, there are more efficient algorithms. For instance, one could use euklid's algorithm to efficiently determine the greatest common divisor, then find its prime factors, and use that to efficiently iterate all divisors.
this works good but the output code is in descending order I need it ascending sadly
Actually, since we take the 1 out of the loop, the order of the loop doesn't matter anymore :-)
System.out.println(1);
boolean divisorFound = false;
for (int i = 2; i <= b; i++) {
if (a % i == 0 && b % i == 0) {
System.out.println(i);
divisorFound = true;
}
}
if (!divisorFound) {
System.out.println("relatively prime");
}
I'm new to Java, so still trying to figure out the syntax and code execution,
I'm working on a very simple algorithm which is basically to return/print true or false statement if a number is divisible by the sum of its digits.
public class Main {
public static void main(String[] args) {
divisableNumber();
}
static void divisableNumber() {
int num = 2250;
int sumOfDigits = 0;
while (num > 0) {
System.out.println(num);
int remainder = num %10 ;
sumOfDigits += remainder;
System.out.println("line17");
System.out.println(sumOfDigits);
num = num /10;
}
System.out.println(num);
// if(num % sumOfDigits == 0) {
// System.out.println( num);
// } else {
// System.out.println(num + "is not divisable by sum of digits");
// }
}
//*****Explanation*********
// java divides by 10 without remainder.
// Hence, can see that with each iteration number is losing its unit digit( it happens end of each loop line21)
// basically with each iteration we are checking what is the remainder of the input divided by 10
// Eventually, we are adding the remainder ( which is the unit digit at each iteration)
}
``
I don't understand why the loop zeros out the variable and how to overcome it ( i could have written another variable inside the loop , but it seems not clean ).
Can anyone help ?
[enter image description here][1]
[1]: https://i.stack.imgur.com/rZbOW.png
Your code prints 0 every time since it divides the number to 10 until it becomes 0 inside the while loop. Remember that any positive number below 10 divided by 10 gives the result 0 in Java.
You calculated the sum of digits correctly but did not check if it divides the number correctly. In order to achieve that, you need to store a copy of number at the start and check if it is divisible by sumOfDigits.
You can achieve the solution with the following code, it is very similar but structured a little better.
class Main
{
// Function to check if the
// given number is divisible
// by sum of its digits
static String divisableNumber(long n)
{
long temp = n; // store a copy of number
// Find sum of digits
int sum = 0;
while (n != 0)
{
int k = (int) n % 10; // get remainder of division of 10
sum += k; // add digit sum
n /= 10; // divide number by 10
}
// check if sum of digits divides n
if (temp % sum == 0)
return "YES";
return "NO";
}
// This is where the execution begins always (main function)
public static void main(String []args)
{
long n = 123; // better to declare number here and give it as a parameter to function
System.out.println(isDivisible(n)); // print the result of divisible or not
}
}
The code below has no output when I run it, I think somehow it is infinite loop? How to fix it?
Write a method named getEvenDigitSum with one parameter of type int called number.
The method should return the sum of the even digits within the number.
If the number is negative, the method should return -1 to indicate an invalid value.
EXAMPLE INPUT/OUTPUT:
getEvenDigitSum(123456789); → should return 20 since 2 + 4 + 6 + 8 = 20
getEvenDigitSum(252); → should return 4 since 2 + 2 = 4
getEvenDigitSum(-22); → should return -1 since the number is negative
public class getEvenDigitSum {
public static int getEvenDigitSum(int number) {
int sum = 0;
int lastDigit=0;
if (number < 0) {
return -1;
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
return sum;
}
}
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
}
OK, and what happens if the number isn't even? You didn't make an else/else if statement after; if your number is odd, it stays the same, the loop is infinite, and hence your code does nothing.
Your condition only handles even digits, but think about what happens when you get a number that contains odd digit, like 1221 for example.
Try adding the missing else statement:
while (number >0) {
lastDigit = number % 10;
if (number % 2 == 0)
{
sum += lastDigit;
number = number / 10;
}
else {
// Deal with odd digit, leaving for you to implement
{
}
General tip: The best way to find errors in your code is to write tests and debug your code.
These are two skills every developer should poses and practice regularly
Beginner here. For my coding class, we have an assignment that requires us to print numbers 1-20, but configure it so that it only outputs even numbers. Here is what I have so far but I'm quite stuck. He says to put an if statement and use the "%" operator but I've no idea where to put them.
int counter = 1;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
//if (counter
System.out.printf("%d ", counter);
counter++;
} // end while loop
Instructions for assignment
My Output
CORRECT Output
if(counter % 2 == 0){
System.out.printf("%d ", counter);
}
counter++;
% operator is mod operator, if counter % 2 == 0 , then counter is an even number
% is an arithmetic operator, it is called MODULO.
Modulo operator returns the remainder of 2 numbers. In this case, we use a modulo to find out whether a number is even or odd.
odd%2 returns 1
even%2 returns 0
The while loop loops through the first 20 elements. So we put an if statement before printing the element. If the counter is an even number i.e (counter%2 == 0) we print that.
This is the code that prints even numbers:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
if (counter%2 == 0){
System.out.printf("%d ", counter);
}
counter++;
} // end while loop
This can also be done without using MODULO operator:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
System.out.printf("%d ", counter);
counter+=2;
} // end while loop
use fori
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
% is the remainder operation
I tried to write a method (for kicks) that would sum up the digits at even places using Java recursion.
For example, the number 23495 would return 3+9 = 12.
I am unsuccessful and would appreciate hints or what I'm doing wrong.
int sumEven = 0;
int sumOdd = 0;
int i = 1;
if (n == 0)
return sumEven;
if (n != 0) {
if (i % 2 == 0)
{
i++;
sumEven += n % 10;
}
else
{
i++;
sumOdd += n % 10;
}
}
return sumEven + getEven (n/=10);
The problem is you're trying to do too much - take a look at my comment on the Q
A recursive method needs an input that contains everything it needs to work with, a return value, and an execution path where it calls itself until something happens that means it doesn't need to call itself any more - without this bit it will recourse until it overflows the stack
int sumEveryOtherDigit(int input){
if(input >= 100)
return input%10 + sumEveryOtherDigit(input/100);
else
return input%10;
}
This takes the input , and if there is any point to running again (if the input is at least 100) takes the rightmost digit plus running itself again with a smaller number
Eventually the number gets so small that there isn't any point running itself again so it just returns without running itself again and that is how the recursion stops
Now from your comment on another answer it seems you want to determine even and odd as working from the left so we need to either start with the number (1630) or the number divided by ten (23495 -> 2349) - basically to start the recursion going we always want to pass in a number with an even number of digits
int num = 23495;
int numOfDigits = (int)Math.log10(num)+ 1;
if(numOfDigits%2==0)
result = sumEveryOtherDigit(num);
else
result = sumEveryOtherDigit(num/10);
You should iterate over the digits of the input number, and then sum the remainder mod 10 only for even position digits:
int input = 23495;
input /= 10;
int sum = 0;
while (input > 0) {
sum += input % 10; // add last even digit
input /= 100; // advance by two digits, to the next even digit
}
System.out.println("sum of even digits of input is: " + sum);
This prints:
sum of even digits of input is: 12