简体   繁体   中英

recognized a numbers and letters in a inputted string

so far i have no problem in getting the length but the recognizing the numbers from letters is hard can any one help me here Thanks for the helps heres the new code my new problem is in counting the elements in the string in will not count the numbers inputted like a Address Example 99 San pedro st philippines ..... it will only count San pedro st philippines .........

import java.util.Scanner;

public class Exercise3
{ 
    public static void main(String [] args)
    {  
        Scanner scan= new Scanner(System.in); 
        System.out.println("Enter String:"); 
        String s=scan.nextLine();
        s = s.replace(" ","");
        System.out.println("Total of Elements is: " + s.length());

        int nDigits =0,nLetters =0,sum =0;
        for(int i =0;i<s.length();i++)
        {
        Character ch = s.charAt(i);
        if(Character.isDigit(ch)){
        nDigits++;
        sum += Integer.parseInt(ch.toString());
    }
        else if (Character.isLetter(ch)){
        nLetters++;
    }
   }
        System.out.println("The sum of numbers in the string: " + sum);
        }
      }
   }

It looks like your problem is with the line sum += Integer.parseInt(s.toString()); . You're taking the string value of the entire InputStream, which is almost certainly what you don't want. I assume you intended to do sum += Integer.parseInt(s.charAt(i).toString()); , which will give you just the value of each individual digit. Take in mind in the string hello43world , it would return 7 (4+3), not 43.

EDIT: To do what you actually want - which is the number of letters in the string, try

public static int getSum(String s)
{
    int sum = 0;
    for(int i = 0; i < s.length(); i++)
    {
        if(Character.isLetter(s.charAt(i)))
        {
            sum ++;
        }
    }
    return sum;
}

This will only count the characters in the string - much easier than trying to not count everything that isn't a character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM