This is a interview question can be asked in an experienced or fresher's interview to write a program which will add up all the integer value present in a string and print the added number.

Tips to think how to do it...

1. For this kind of problem always think of first matching the number in a String .
2. How you are going to match?
3. The only simplest way is with the help of ASCII of 0-9 .

Steps to do :

1. Take a int variable c=0.
2. Run the loop from 0 to String length.
3. Get the each index value using charAt() method which will return the char value.
4. Convert that char into int by typecasting or any other way.
5. Now check that ASCII fall into the range of 48-57 for 0-9 int number.
6. If it matches then first convert that number into integer using Integer.parseInt().
7. Then add with the c and store to the same variable i.e c.
8. Repeat from 3-7 till the end of the loop.
9. At the end of loop , Print c outside the loop.

Program


public class Lab1 {

   public static void main(String[] args) {
 
 String s="s16u7ty9";
 int c=0;
 for(int i=0;i<s.length();i++){
    char ch=s.charAt(i);         // Getting each char from String
    int x=(int)ch;               
    for(int y=48;y<=57;y++){       // Loop for checking the ASCII
       if(x==y){
   int num=Integer.parseInt(""+ch); //Getting the int value
   c=c+num;
       }
    }
 }
 System.out.println("Total Sum:"+c); // Final sum 

   }

}






Related Posts:

  • Anonymous class in Java Like other classes in java , anonymous is also a type of class but it doesn't have any name like other classes have their own name either defined by the user or pre-defined in the java by the java vendors. So anonymous class… Read More
  • Inner Class in Java Inner class in a class defined as a class inside another class. So it is itself a class but first it will act as a member of that class. As we know that we cannot make a class as static but inner class can be made as static… Read More
  • Local inner class in Java Local inner class is a class which is define local to the outer class. So it must be defined within the local scope of a class like method, constructor or initialization block . A class within a class in never treated as the… Read More
  • Static inner class in Java Like Instance inner class we have also static inner class. Static instance class is loaded at the time of loading the outer class as it is declared as static that means it will act as the static member of the outer class and… Read More
  • Instance Inner class in Java As the name itself indicates that inner class with non-static scope that means a member of outer class which is of instance scope called as instance inner class. Instance inner class is itself a class but we cannot use any s… Read More

4 comments:

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

201978

Online Members

Live Traffic