Reputation: 607
Hi my program is supposed to display the number of digits entered at the command line. It does this but my formatting on the answer is wrong. I'm getting outputs in the form "Number of Digits in0is2" when I enter "22" for example.
Can anyone tell me what I'm doing wrong?
import java.util.Scanner;
public class test {
public static void main(String args[]){
int n;
int i=0;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
while(n>0)
{
n=n/10;
i++;
}
System.out.println("Number of Digits in" +n +"is" +i);
}}
Upvotes: 0
Views: 113
Reputation: 757
Write code like this.
import java.util.Scanner;
public class HelloWorld {
public static void main(String args[]){
int n;
int i=0;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
int a=n;
while(n>0)
{
n=n/10;
i++;
}
System.out.println("Number of Digits in=" +a +"is" +i);
}}
You save the n
value in the other variable and that variable print with i
variable and execute code and show output
Upvotes: 0
Reputation: 6181
You are printing the n
which is 0
after you while loop. You need to store the number in another variable and use that variable when printing.
Try this:
import java.util.Scanner;
public class Test2 {
public static void main(String args[]){
int m,n;
int i=0;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
m=n;
while(n>0)
{
n=n/10;
i++;
}
System.out.println("Number of Digits in " +m +" is " +i);
}
}
If you don't want to use m
variable then:
public static void main(String args[]){
int n;
int i=0;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
System.out.print("Number of Digits in " +n +" is ");
while(n>0)
{
n=n/10;
i++;
}
System.out.println(i);
}
Upvotes: 1
Reputation: 735
There is a logic error in your program.
For example you entered '22' then in the while loop:
while (n>10){
n = n/10;
i++;
}
it will just keep dividing n and increasing i until n reaches 0.
At the end of the while loop n is 0, its no longer '22' as you entered. To solve this you should use a temporary variable say 'tmp'
public static void main(String args[]){
int n;
int i=0;
int tmp = n;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
while(tmp>0)
{
tmp=tmp/10;
i++;
}
System.out.println("Number of Digits in " +n +" is " +i);
}
Note in your initial code, you forgot to add a whitespace in the System.out.println()
:D
Upvotes: 1
Reputation: 3819
The variable n
is devided by 10 till it becomes 0, then you try to print it hence you get wrong output.
This should work fine
public class test {
public static void main(String args[]){
int n;
int i=0;
System.out.print("Enter a Number:");
Scanner scanner = new Scanner(System.in);
n= scanner.nextInt();
int backUp = n;
while(n>0)
{
n=n/10;
i++;
}
System.out.println("Number of Digits in " +backUp +" is " +i);
}}
Upvotes: 2