Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making an Armstrong number checker but if condition is not working

I was Making A Armstrong number checker not for only 3 digits numbers for wich i used Math.pow() method but after using it the if else statement is not working also when the condition is true.
Here is the code.

import java.util.Scanner;
import java.lang.Math;
class Main {
 ////////////////////////////////////////////

 ////////////////////////////////////////////
 public static void main(String args[])
{
 System.out.println("Hello world!");
 Scanner sc = new 
 Scanner(System.in);
 int num = sc.nextInt();
 int  numc = num ; 
 double rem = 0;
 double cu = 0;
 int val = 0;
 int val2 = 0;
 
 
 while(num != 0){
  rem = num%10;
  
  while(numc != 0){
   numc /=10;
   int i = 0;
   i++;
   val2 += i; 
  }


  cu = Math.pow(rem,val2 );
  val += cu; 
  num /= 10;
 }


 if(val == numc){
    System.out.println("Yes its a "+val2+"  Armstrong number because its returning " + val+"after Calculations ");
   }
   else{
     System.out.println("No its not a "+val2+" digit Armstrong number because its returning " + val +" after Calculations ");
            
           }
 
}
}
///////////////////////////////////////////

Compiling this code in terminal

And this is the Compilation of my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

if(val == numc){ – This if part is the root cause of your problem . you are dividing numc by 10 for calculations . So at the end it will become 0 . so you will be checking if val == 0 which goes to the else loop.

So I would suggest to assign the input from the user to another variable which you can use for checking the final if – else part.

Like int input = num and at the end if(val==input){ . This would resolve your issue.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading