I've written code to print the digits of an integer on separate lines, but I am not getting the expected output. The output of the code is instead in reverse order. How can I make my output correct without using the Math.pow method?
import java.util.Scanner;
class NumberInDigit
{
public static void main(String[] args)
{
int div;
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
int n = sc.nextInt();
while(n>0)
{
div = n%10;
n= n/10;
}
System.out.println(div);
}
}
n = 234
Output is 4,3,2
Expected output is 2,3,4
The "%" is the modulo operator so div = n%10; takes n (234), then finds the remainder the 234 when divided by 10. 234/10 = 23.4 (i.e. 4 is the remainder). So div is assigned a value of 4 (i.e. div = 4). Then you are dividing n (234), by 10 and reassigning it to n - so (234 / 10 = 23), note the remainder is ignored.
That is the end of the first iteration of the loop, and it returns div = 4.
The second iteration (when n = 23) will print out 3 (because 23 / 10 = 2r3) - remember we are returning the remainders. N is then set to 2.
The third itereration (when n = 2) will print out 2 (because 2/10 = 0r2) - the remainder is 2. N is now set to 0 as (2 / 10 = 0). So then next iteration will fail the condition of n > 0.
This is why you are getting 4,3,2.
There are a number of ways to get the expected number, but since you are working in base10 (i.e. the decimal system), I think the easiest would be just to convert the number into a string and then iterate through the string printing every number until you reached the end, or a decimal point.
you are dividing division Remainders and again dividing them again, if you want to operation on string use array
You can do it this way also:
int n=234,x=n,y=100;
while(x>=0)
{
x=n/y;
n=n%y;
System.out.println(x);
y=y/10;
}
This way output is 2,3,4.
First of all your code has syntax and logical issues. "n" doesn't have a type and it should only return 4 (since you are executing return it should not continue the while loop).
To accomplish what you need you can change your code a bit:
public static void main(String [] args){
System.out.println(printReversedNumList(234));
}
private static List printReversedNumList(int num) {
final List<Integer> reversedNumList = new ArrayList<>();
while(num>0)
{
int remainder = num%10;
num= num/10;
reversedNumList.add(remainder);
}
Collections.reverse(reversedNumList);
return reversedNumList;
}
Related
Given an int in Java, I want to be able to determine the digit in the hundreds place of the number. For example:
an input of 124 should give an output of 1
an input of 357 should give an output of 3,
an input of 653 should give an output of 6.
I have tried the code below, but am getting the following error:
The operator / is undefined for the argument type(s) boolean, int
Here is my code:
import java.util.Random;
class adam{
public static void main(String[]args)
{
Random rnd = new Random();
int first = rnd.nextInt(900)+100;
int second = rnd.nextInt(900)+100;
int third = rnd.nextInt(900)+100;
System.out.println(first);
System.out.println(second);
System.out.println(third);
if ((first==second&&first==third)/100);
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Question
How can I get the digit in the hundreds place value from a Java int?
Why am I getting this error in my code?
Let me guess, you probably want something along these lines:
if (first / 100 == second / 100 && first / 100 == third / 100) {
System.out.println(first / 100);
System.out.println(second / 100);
System.out.println(third / 100);
}
This will print the same value three times if the condition is true, though, which may not be exactly what you want. For example, if the numbers are 756, 723 and 792, it will print 7 three times. Anyway, you can try it out, see if you can modify it to your needs, and if not, explain where I guessed wrong.
Edit: to reduce the number of divisions you can alternatively just divide all the values by 100 before the if statement:
first /= 100; // or if you prefer: first = first / 100;
second /= 100;
third /= 100;
if (first == second && first == third) {
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
How can I get the digit in the hundreds place value from a Java int?
You're on the right track with your integer division. You've also got the modulo operator at your disposal for handling numbers >= 1000.
Easiest to just show the math, this should be enough for you to go on:
2468 (1) start with an integer, 2468
2468 / 100 = 24 (2) divide by 100 to discard 10's and 1's
24 % 10 = 4 (3) modulo 10 to discard 1000's and higher
4 (4) and your left with your 100's digit
As you can see, you could stop at (2) if you know you won't see numbers >= 1000. As an aside, you'd want to take the absolute value first if you have to deal with negative numbers.
Why am I getting this error in my code?
Because this statement is nonsense:
if ((first==second&&first==third)/100);
In particular the condition is:
(first==second&&first==third)/100
And if you split it into its parts you can see what is happening:
first == second (1) == produces a boolean
first == third (2) == produces a boolean
(1) && (2) (3) && produces a boolean
100 (4) 100 is an int
(3) / (4) (5) now you have boolean / int
And you can't divide a boolean by an int.
How can I get the digit in the hundreds place value from a Java int?
This code is working:
import java.util.Random;
class Adam{
public static void main(String[]args)
{
Random rnd = new Random();
int first = rnd.nextInt(900)+100;
int second = rnd.nextInt(900)+100;
int third = rnd.nextInt(900)+100;
System.out.println(first);
System.out.println(second);
System.out.println(third);
int first1=first/100;
int second1=second/100;
int third1=third/100;
System.out.println("an input of "+first +" an output of "+first1 +" first");
System.out.println("an input of "+second +" an output of "+second1+" first");
System.out.println("an input of "+third +" an output of "+third1+" first");
}
}
Why am I getting this error in my code?
--->The boolen can't devided by an int
All you need is the third last digit in the number.
So you can try this:
String temp = number + "";
System.out.println(temp.charAt(temp.length() - 3));
import java.util.Scanner;
public class SumDigits {
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
// prompt the user to enter a value and store it as the integer called number
System.out.print("Enter an integer: ");
double number = Math.abs(input.nextDouble());
System.out.println("The sum of the digits is " + sumNumbers(number));
input.close();
}
public static int sumNumbers (double number)
{
int sum = 0;
for (int i = 10, digit = 0; (number * 10) /i !=0; i *= 10, digit = (int)((number % i) - digit)/(i / 10))
{
sum += digit;
}
return sum;
}
}
At runtime, I get the error message
Exception in thread "main" java.lang.ArithmeticException: / by zero
referring to line 25 (my for loop conditions).
The loop worked fine until I tried type casting digit's value to an int, and I'm not really certain why that would cause any part of the loop to divide something by zero. I've gone over all the possibilities regarding the conditions that use rational expressions and can't deduce a contingency wherein any denominator would be set to zero. I get this error regardless of what number is input. I would not have chosen to save number as a double at all if it were not for the fact that my professor provided a number whose value exceeds that which can be stored within an int in one of his test cases. The program ran fine prior to the type cast and provided the correct answer for all other test cases.
Here you are doing
(number * 10) /i !=0
where number is double.
Floating point numbers aren't recommended for comparisons because of the way they get stored (in mantissa and exponent form). So, if this condition returns true, consider yourself lucky.
Because of that your loop is kinda never-ending loop. The reason you are getting arithmetic exception though is that here you are multiplying i by 10 in this kinda infinite loop. "i" reaches "integer" limit of 32 bits and overflows and ultimately makes all those 32 bits as 0.
Effectively, i=0 and both of the following throw divide by zero exception
(number * 10) /i
and
(number % i) - digit)/(i / 10)
The root cause of the ArithmeticException is the incorrect loop condition. Adding System.out.println("i=" + i + " i*10=" + (i * 10)); in the loop produces output:
i=10 i*10=100
i=100 i*10=1000
i=1000 i*10=10000
i=10000 i*10=100000
i=100000 i*10=1000000
i=1000000 i*10=10000000
i=10000000 i*10=100000000
i=100000000 i*10=1000000000
i=1000000000 i*10=1410065408
i=1410065408 i*10=1215752192
i=1215752192 i*10=-727379968
i=-727379968 i*10=1316134912
i=1316134912 i*10=276447232
i=276447232 i*10=-1530494976
i=-1530494976 i*10=1874919424
i=1874919424 i*10=1569325056
i=1569325056 i*10=-1486618624
i=-1486618624 i*10=-1981284352
i=-1981284352 i*10=1661992960
i=1661992960 i*10=-559939584
i=-559939584 i*10=-1304428544
i=-1304428544 i*10=-159383552
i=-159383552 i*10=-1593835520
i=-1593835520 i*10=1241513984
i=1241513984 i*10=-469762048
i=-469762048 i*10=-402653184
i=-402653184 i*10=268435456
i=268435456 i*10=-1610612736
i=-1610612736 i*10=1073741824
i=1073741824 i*10=-2147483648
i=-2147483648 i*10=0
First time control enters into loop the value of digit would be zero and not the last digit of entered number as you would have expected. Also you need to fix your loop termination condition as that is wrong. For example if number is 123 then at last expected iteration 1230/1000 = 1 and not 0 and loop does not end and rather leads to overflow. You can use the following:
public static int sumNumbers (double number)
{
int sum = 0;
for (int i = 10, digit = (int)(number % i); digit != 0; i *= 10, digit = (int)((number % i) - digit)/(i / 10))
{
sum += digit;
}
return sum;
}
This should work but I again recommend you to improve this code as this is not the ideal way.
Testing:
Enter an integer: 3456
The sum of the digits is 18
Hello everyone I was having some issue splitting up a user input number using printf (I do have to use printf). My problem is that when I put in say the number 12345 it will print the integers on five separate lines, and also has them in the reverse order. So it would look something like this when I put in the integer 12345:
5
4
3
2
1
But without the spaces (I need those as well). I want it to print like this: 1 2 3 4 5.
Here is the code I have so far:
public static void main(String[]args){
Scanner input = new Scanner(System.in);
int one;
System.out.print("Enter the five digit integer you would like to be split up:");
one = input.nextInt();
while (one > 0){
System.out.printf("%d%n", one % 10);
one = one /10;
}
}
First, in order to avoid printing on separate lines, you should avoid using the %n formatting character in your printf().
Now, how do you print the digits in the correct order? Well, since you are limited to five-digit numbers, you can do something like this:
for ( int divisor = 10000; divisor >= 1; divisor /= 10 ) {
System.out.printf( "%d ", n / divisor);
n %= divisor;
}
System.out.printf( "%n" ); // Just to complete the line
(divisor /= 10 is shortcut for divisor = divisor / 10, and n %= divisor is shortcut for n = n % divisor).
So you start by dividing the number by 10000. This will give you the fifth digit from the right. Then you take the remainder and put it in n. This gives you just the remaining four digits. Then the loop will reduce your divisor to 1000, which will take the fourth digit from the right, and you keep doing that until you reach a divisor of 1.
Another approach that does not require knowing that the number is 5 digits long, but requires recursion is to write a method like so:
public static void printSplitNumber( int n ) {
if ( n == 0 ) {
return;
}
printSplitNumber( n / 10 );
System.out.printf( "%d ", n % 10);
}
And from your main, call:
printSplitNumber(n);
System.out.printf("%n"); // Again, just completing the line.
This recursive method relies on the fact that you print the current digit only after all the rest of the number has been printed. So this causes it to print it to the right of the rest of the digits, giving you the effect you need.
Unless the assignment is to figure out how to split the digits numerically, I think that the simplest approach is to either use Scanner's nextLine() method to get a String, or convert your int to a String, and then split the characters of the String.
substring() is a little heavy - a lighter-weight way to do it is by inspecting character positions, like this:
public void printDigits(String chars) {
for(int i = 0; i < chars.length(); i++) {
System.out.printf("%c ", chars.charAt(i));
}
}
This approach uses the substring method as opposed to mathematically manipulating the int value.
int one;
System.out.print("Enter the five digit integer you would like to be split up:");
one = input.nextInt();
String x = Integer.toString(one);
for(int i = 0; i < x.length() - 1; i++)
{
// On last digit in number
if(i + 1 == x.length())
{
System.out.printf("%s ", x.substring(x.length()));
}
else
{
System.out.printf("%s ", x.substring(i, i + 1));
}
}
Simplified printf statemnts thanks to #Jerry101's comment
I have to write a code for printing all palindrome numbers up to 1000. Here is my code. I have dealt with 3 scenarios:
1-digit number
2-digit number
3-digit number
My third scenario is not printing just the palindromes but prints all the numbers. A hint will help me solve this.
public class PrintPalindrome {
public static void main(String args[])
{
Integer[] array=new Integer[1000];
for(int i=0;i<array.length;i++)
{
array[i]=i+1;
printPalindrome(array[i]);
//System.out.println(array[i]);
}
}
public static void printPalindrome(Integer a)
{
String num=Integer.toString(a);
int length=num.length()-1;
//System.out.println(num);
if(num.length()<=1)
{
System.out.println("" + num);
}
else if(num.length()==2)
{
if(num.charAt(0)==num.charAt(1))
System.out.println(num);
}
else if(num.length()>2)
{
//now deal with the numbers whose length is greater than 2
for(int i=0;i<=length;i++)
{
if(num.charAt(i)==num.charAt(length-i))
System.out.println(num);
}
}
}
}
Work out a solution with arithmetic…
This doesn't necessarily help with the code that you've already got, but it's approach to the problem in the title, How to print all palindromes upto 1000, which may be helpful to others who come across this question. It's often fun to try to solve these problems using the properties of the numbers, without worrying about converting them to strings. In this case, note that for any number n, you can get the leading digit by n % 10, that is, the remainder of n divided by 10, or n modulo 10. You can get the number whose digits are the same as the remaining digits of n as the integer quotient of n/10. E.g.,
1234 % 10 = 4
1234 / 10 = 123
Now, if you keep applying this deconstruction, you can get the individuals digits:
123 % 10 = 3
123 / 10 = 12
12 % 10 = 2
12 / 10 = 1
1 % 10 = 1
1 / 10 = 0
Now, if you take those numbers in the same order that you got them (4, 3, 2, 1), you can reconstruct the "reverse" number:
1 + 10(2 + 10(3 + 10(4 + 0))) = 4321
If we call this the reverse of a number, then number is a palindrome if and only if it's equal to it's reverse.
…and then translate it to Java
This is fairly straightforward to implement in Java, and it doesn't require any special casing about 1-digit numbers, 2-digit numbers, etc., or string manipulation. (As Kent points out in the comments, there's still a limit on how large the numbers that this handles is, but if you need to handle big numbers, you could (i) switch to a long; (ii) switch to a BigInteger.)
public class PalindromeExample {
/**
* Returns the number whose digits (base 10) are the reverse
* of number's (with no leading zeros).
* #param number the number to reverse
* #return the reversed number
*/
public static int reverse( int number ) {
int result = 0;
while ( number > 0 ) {
result = result * 10 + (number % 10);
number = number / 10;
}
return result;
}
/**
* Show the numbers less than 10000 whose digit sequences
* are palindromes.
*/
public static void main(String[] args) {
for ( int i = 0; i < 10000; i++ ) {
if ( i == reverse( i ) ) {
System.out.println( i );
}
}
}
}
0
1
2
3
…
9
11
22
…
99
101
111
…
151
161
…
8008
8118
…
9339
9449
9559
9669
9779
9889
9999
if(num.charAt(i)==num.charAt(length)-i)
is wrong. Even if you set parenthesis in the "right" place you still be wrong, because for example:
charAt(0) == charAt(3) //and what's char at 3?
if(num.charAt(i)==num.charAt(length-i-1))
should do the trick but then placing it in a for loop doesnt make any sense.
When a 3-digit number has 1st and 3rd digit the same it is actually a palindrome. Every other loop will just mess up your output.
For the requirement, we don't have to convert to string.
pls try if this works for you: (could be an one-liner)
for (int i = 1; i < 1000; i++)
if (i<10 ||(i<100&&i%11==0)||(i>100&&i%10==i/100) )
System.out.println(i);
Handling scenarios for each digit length to check if a number is a palindrome is not an appropriate approach.
Trying what the other answers suggest - like going through each and every number and checking if it is palindrome by reversing number digit by digit is better but even then it is not very efficient as it is brute force.
So, I would like to some suggestions if I may:-
Rather than going for brute force, any other approach if possible is preferable.
Even while resorting to brute force, using the library functions is
better and at least as efficient as any code we can write. ex - Integer.reverse() function for reversing an integer.
I have had a try at generating the palindromes(rather than trying one by one). This is not bug-proof yet as I have not tested extensively but should be able to convey the concept.
public class PrintPalin {
public static void main(String[] args) {
// TODO Auto-generated method stub
//The first palindrome = 1
int i = 1;
while(i<=10000){
System.out.println(i);
i = nextPalin(i);
}
}
static int nextPalin(int i){
StringBuilder sb = new StringBuilder(String.valueOf(i));
int len = sb.length(), right = len/2, left;
if(len%2!=0 || len == 1){
left = right;
}else{
left = right-1;
}
//System.out.println(left + " " + right);
while(right<len && sb.charAt(right)=='9'){
sb.setCharAt(right, '0');
right++;
sb.setCharAt(left, '0');
left--;
}
if(right==len){
sb.insert(0, '1');
//sb.append("1");
sb.setCharAt(right, '1');
}else{
sb.setCharAt(right, (char)(sb.charAt(right)+1));
if(right != left){
sb.setCharAt(left, (char)(sb.charAt(left)+1));
}
}
i = Integer.valueOf(new String(sb));
return i;
}
}
Where the above approach wins is when the density of palindromes per number tried is less when we go for higher numbers but for the range that is asked(0 to 1000) it would not be able to make much difference.
I am open to other approaches. I was thinking may be decoding the addition required to generate the next palindrome number should be faster and better approach instead of using strings the basic idea of both approaches are similar so should not be much difficult(though I am not sure).
I believe you want to check whether the number is a palindrome or not before you print it. You just need to seprate checking and printing like this:
if(num.length()>2)
{
boolean isPalindrome=true;
for(int i=0;i<=length/2;i++) //you compare one half, to the other
{
if(num.charAt(i)!=num.charAt(length-i))
isPalindrome=false;
}
if(isPalindrome)
System.out.println(num);
}
This should work for a number of any length.
my question is not so much about code as it is the logic behind writing a factorial program. I am currently taking a MOOC at the University of Helsinki and I have become stuck on this exercise. As the course moves on to new exercises the instructions have become more and more vague. I realize this probably isn't the place to ask this question and if you must tag it or remove it, I do understand. I am trying to learn this on my own as I do not have the time or money to actually attend a university. This course has no time constraint and I wont be receiving a certificate of achievement for it, I simply want the knowledge.
these are the instructions given for the exercise
Create a program that calculates the factorial of the number n. The factorial n! is calculated using the formula 1*2*3*...*n. For example 4! = 1*2*3*4 = 24. Additionally, it is defined that 0! = 1.
// i don't understand the example that 4!= 1*2*3*4 = 24
// or how 0! = 1 pertains to multiplying numbers in succession to find the
// factorial of the user input number.
// i understand that 0! = 1 simply delclares that 0 is not equal to 1
// and 4 is not equal to 24, however if the 4! = portion of this statement
// is in reference to the user input number 4 that statement would not be
// true as 1*2*3*4 does equal 24 and 4 would be the number of executions
// of the block execution of the loop required to write the factorial
// program.
// EDIT: okay so according to this http://en.wikipedia.org/wiki/Factorial
// i am wrong about what is being done here as they are not declaring
// that 4 not equals 24 but yet that 4! is a way of correlating the non
// negative numbers up to 4, but given that math is not my strong suit
// it is even more confusing to me as to what i should be doing.
Example outputs:
Type a number: 3
Factorial is 6
Type a number: 10
Factorial is 3628800
my current code attempt is as follows
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int userIn = Integer.parseInt(reader.nextLine());
int factorial = 1;
int extra = 1;
int sum = 0;
while (factorial <= userIn) {
factorial++;
sum = factorial + userIn + extra;
}
System.out.println("The factorial is:"+sum);
}
}
I do not understand what it is that i am missing, i know from research that in the real world you would not code this as there are libraries you can download to perform the factorial function that are much more efficient than what i could code, but i don't want to simply skip this exercise with the knowledge that someone else has already coded and created a library to make our lives easier, i want to learn everything that this course has to offer. if i have made a simple error i don't mind an offered code correction, however i want to understand what makes the factorial operation tick so to speak, not just be given the answer so i can move on.
The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. Eg:- 4!=1*2*3*4 . 0!=1 states that factorial of 0 is 1 and not that 0 is not equal to 1. The value of 0! is 1, according to the convention for an empty product. An empty product, or nullary product, is the result of multiplying no factors. It is by convention equal to the multiplicative identity 1 , just as the empty sum—the result of adding no numbers—is by convention zero (Like the sum of first 0 natural numbers would we 0), the additive identity.
For more on empty products read here http://en.wikipedia.org/wiki/Empty_product
For the programming part, there are basically two approaches to a factorial program:-
Using a for loop (No recursion)
int factorial ( int input )
{
int x, fact = 1;
for ( x = input; x > 1; x--) // iterating from n -> n-1 -> n-2 ... 1
{
fact *= x; // multiplying each number into the fact variable to get the factorial
}
return fact;
}
Recursive approach -The function calls itself ( Note- avoid using this approach in actual programming as it may be highly resource consuming and bug prone, As pointed out by "Edwin Buck" in the comments)
public int Factorial(int n)
{
if (n == 0)
{
return 1; //Base condition - If factorial reaches 0 return 1 and end recursion
}
else
{
return n * Factorial(n-1); // For factorial of n, function returns n * Factorial(n-1) i.e recursively calling the factorial function with one less value in the parameter untill 0 is reached (upon which base condtiion will be evaluated)
}
}
Try this one if you don't want to use an external function
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int userIn = Integer.parseInt(reader.nextLine());
int factorial = 1;
int i= userin;
while (userin >= 1) {
factorial *= userIn;
userin--;
}
System.out.println("The factorial is:"+factorial);
}
}
The problem is here
sum = factorial + userIn + extra;
where you "calculate" your factorial from the latest factorial++ value in the loop.
You can't calculate factorials from sums in this manner. Factorials are products of all the integers between 1 and the "factorial" number, so
1! = 1
2! = 1 * 2
3! = 1 * 2 * 3
4! = 1 * 2 * 3 * 4
If you start off calculating your factorial wrong, then the other parts of the problem don't matter much, they will be wrong by extension.
// Factorial example (ie 5 * 4 * 3 * 2 * 1)
function factorial($n) {
if ($n == 1) return 1;
return $n * factorial($n-1);
}
echo factorial(5); // Outputs 120
// Nested Array Summing Example
$example = array(1, 2, array(10,20,30), 4);
function sum_array($array) {
$total = 0;
foreach ($array as $element) {
if(is_array($element)) {
$total += sum_array($element);
} else {
$total += $element;
}
}
return $total;
}
echo sum_array($example); // Outputs 67
Your question is similar to mine, and it was actually a school assignment.
Though question is answered, i will contribute my solution.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int i = 1;
int factorial = 1;
System.out.println("Give number: ");
int number = Integer.parseInt(reader.nextLine());
while (i <= number) {
factorial = factorial * i;
i++;
}
System.out.println("Answer is " + factorial);
}