How to find number of digits in a number java?
Problem:


Hello all,

I am a secondary school level student and recently started learning Java programming out my curiosity. I have got a textbook on Java programming. I just completed the chapter of for-loop and continue solving the exercises of this chapter. I have got weird a problem says to find the number of digits in a number using a java program.

Being a novice, I really don’t have any idea about this. Could anybody here answer my question, please? I know it’s might be a dumb question for you guys. But, yeah it is important to know for me. Thanks for being nice to me. I must recognize your help.

Thanks.
Solution:


Hello Gavin,

You have got a nice question. No matter how the question is, don’t forget to ask. Thanks.  
There are a couple of ways to find the number in digits in a number. As you told you just started learning and well-known with the for-loop. I am trying to solve the problem using a simple iteration. Please have a look below program. I hope the program will clarify itself to you as you’ve covered the for-loop topic already.


```
public class DigitsInNumber{
    static int countDigit(long x){ 
        int counter = 0; 
        while (x != 0) { 
            x = x / 10; 
            ++counter; 
        } 
        return counter; 
    }

  	public static void main(String[] args){ 
        long x = 1052809467; 
        System.out.print("Number of digits : " + countDigit(x)); 
    } 
}
```
Thanks again. Good Day!
(a) for digit



expression : 5n + 1

where n = no of digits

for 5 digits

no of segments required = 5(5) + 1 = 25 + 1 = 26

for 10 digits

no of segments required = 5(10) + 1 = 50 + 1 = 51

for 100 digits

no of segments required = 5(100) + 1 = 500 + 1 = 501

(b) for digit



expression : 3n + 1

where n = no of digits

for 5 digits

no of segments required = 3(5) + 1 = 15 + 1 = 16

for 10 digits

no of segments required = 3(10) + 1 = 30 + 1 = 31

for 100 digits

no of segments required = 3(100) + 1 = 300 + 1 = 301

(c) for digit



expression : 5n + 2

where n = no of digits

for 5 digits

no of segments required = 5(5) + 2 = 25 + 2 = 27

for 10 digits

no of segments required = 5(10) + 2 = 50 + 2 = 52

for 100 digits

no of segments required = 5(100) + 2 = 500 + 2 = 502 Here, this should do it. I just replaced the

 
```
System.out.println(isPrime(n));

```
 part, which would print true or false, with an if

 
```
if (isPrime(n))
    System.out.println("The number is prime.\n");
else 
    System.out.println("The number is not prime.\n");

```
 Here's the code:

 
```
import java.util.Scanner;
public class PrimeNumber{
    public static void main(String args[]){
        int n;
        Scanner Prime = new Scanner(System.in);
        System.out.println(" Please enter a number: ");
        n = Prime.nextInt();
        if (isPrime(n))
            System.out.println("The number is prime.\n");
        else 
            System.out.println("The number is not prime.\n");
    }

    static boolean isPrime(int n) {
        if (n%2==0)return false;
        for(int i=3;i*i<=n;i+=2) {
            if(n%i==0)
                return false;
        }
        return true;
    }
} 

```
 This is a trivial task. You should probably read your coursebook/tutorials, I bet you'll find the answers there. I will preface this by saying that I don't know Java at all. I touched upon it in school 20+ years ago, but I've been doing PHP ever since.


However, on line 27, you say that if the input passed in is a double, execute this code block *blah*.


The user enters -1.


Is -1 not a double? It is a valid double, and therefore the code block executes, setting the priceFromUser to be -1 and adding it to the list.


Then, when the loop starts back up again on line 23, priceFromUser is now -1, so the loop breaks and prints the tally.


Also, note you're definining this constant SENTINEL variable, but you're not actually using it anywhere in your code.


Perhaps do something like this instead, changing the while loop into a do-while loop:



```
System.out.println("Please enter item price to start, since there needs to be at least 1 item:");

do
{

        // Keep asking for a price until the user enters a valid price
        while (!in.hasNextDouble())               
        {
                trash=in.nextLine(); //throw away the input 
                System.out.println("You did not enter a valid price. Please try again:");
        }

        priceFromUser=in.nextDouble(); //read value from user
        list.add(priceFromUser); //add valid price to the list            

          System.out.println("Please enter another item price, or enter -1 to quit.");

} while (priceFromUser != SENTINEL)
```

Note this isn't valid code because I'm not a Java programmer, but hopefully it helps you out a bit. so finding the square root by vedic method, four digits are in the number, so the digits in it’s square root will be 2. the quotient is 46, so the square root is 46.hint –i. four digits in the number so two digits in the square root.ii. first square root digit = 4iii. 21 - = 5 = remainderiv. pair of digits 16 was descended before 5. so new dividend = 516.v. divisor = 4 2 = 8, i.e., double of square root digit.vi. 86 divides 516 by 6, so write 6 ahead digit 4 in the quotient.vii. 516 – 86 6 = 516 – 516 = 0remainder = 0, square root = quotient = 46. the octal numbering system is very similar in principle to the previous hexadecimal numbering system except that in octal, a binary number is divided up into groups of only 3 bits, with each group or set of bits having a distinct value of between 000 (0) and 111 ( 4+2+1 = 7 ). the octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7. octal number system is one the type of number representation techniques, in which there value of base is 8. the number system whose base is 8 is known as the octal number system. octal number system is a base-8 number system where the range of numbers is 0,1,2,3,4,5,6,7. octal number system watch more videos at https://www. What do you have to do when you want to learn swimming?  

Jump into undeep water and train yourself, until you can swim. That way you will be able to swim in very deep water.


Same with programming: start small and get more and more programming experience every day.  

If you encounter problems, you alway s can ask here at DaniWeB. Success! Hi Valdeth. You should use input and output file streams if you want to write and read from a file. Basically you open the file for writing and once you are done close the file. Later you can open the file for reading. The example below reads numbers from the file and just prints them out. If you want to read the file line by line you should look at the getline() function. I have just used your initial array to come up with a result per array which gives the product of all negative numbers in the array. Note that there **HAS** to be at least 1 negative number per array.



```
const int m=4, n=5;
	int i,j;
	int num;
	int result;
	int A[m][n]={{5,3,-4,8,2},
				 {1,5,2,7,-8},
				 {-3,9,5,2,4},
				 {4,-1,3,6,8}};

	ofstream outfile;
	ifstream infile; 

	outfile.open("c:/matrix/matrix.txt");

	for (i=0;i<m;i++)
	{
		result = 1;

		for (j=0;j<n;j++)
		{
			outfile << setw(3)<< A[i][j];

                            // Multiply negative numbers in each array (has to be at least 1 negative number in each array)
			if (A[i][j] < 0)              				                      result *= A[i][j];  // result = result x A[i][j]
		}
		cout << "Result of array " << i << " is " << result << endl;
		outfile << "\n";
	}

	outfile.close(); // Close for writing

	infile.open("c:/matrix/matrix.txt"); // opens the file
    
	infile >> num;
	while ( !infile.eof() ) 
	{ // keep reading until end-of-file
		cout << "The next number is " << num << endl;
		infile >> num; // sets EOF flag if no value found
	}
	infile.close();  //Close for reading
``` Your explanation is not consistent. You state that the user is to enter a range as in "find me all numbers between x and y that are divisible by both 3 and 4." Later you state that you "input value 120 10 times". That is inconsistent with the problem so either the problem is stated incorrectly or you are not inputting the expected data. Decide what is the correct problem then write it up in pseudo-code before you write the actual code.


If a range is expected, make sure you test that it is a valid range (x <= y). `for i in count:` means `for i in 7:`, which won't work. The bit after the `in` should be of an iterable type, not a number. Try this:



```
for i in range(count):

``` HM ok, another day, another try, but I gotta say: The seemingly endless lessons about numbers and numbers on top of numbers and more numbers are really disencouraging me a lot. It's been a lot of fun up to this point, but I really don't see the point in filling out so much about numbers for the sake of numbers o\_o Could you, like, do a little less of that?