TAKING A STRING AND PRINTING ONLY THE DIGITS

Samuel Fernandes

Total Post:159

Points:1117
Posted by  Samuel Fernandes
Java 
 897  View(s)
Ratings:
Rate this:
This is the code that I have so far, It will only print out the digit if it is entered first..How to I get it to print out all digits? and I am getting an error that the c is not initialized
import java.util.*;
 
//Write a program that prompts the user for some text.  Output only the digits in that text.  Hint:  Use a loop and the Character.isDigit method.
public class Q1 
{
     
    public static void main (String[] args)
    {
        String user_input;
        char c;
        Scanner keyboard = new Scanner (System.in);
         
        user_input = keyboard.nextLine();
         
        for( int i=0; i<user_input.length(); i++)
        {
        c = user_input.charAt(i);
        }
         
        if(Character.isDigit(c))
        {
            System.out.println(c);
        }      
          
    }   
}//end code
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Taking a string and printing only the digits

    You print statement does not appear in your for-loop. This means that there will only ever be at-most one print statement executed. If you want to print out every digit then you need to move the print statement into the for-loop.

    Are you sure it only prints digits that appear first though? It looks to me like the local variable 'c' will only ever contain the final character from the String

    import java.util.*;
     
    //Write a program that prompts the user for some text.  Output only the digits in that text.  Hint:  Use a loop and the Character.isDigit method.
    public class Q1
    {
        
        public static void main (String[] args)
        {
            String user_input;
            char c = 0;
            Scanner keyboard = new Scanner (System.in);
            System.out.println("Enter some text:");
            user_input = keyboard.nextLine();
            
            System.out.println("Here are the digits in that text: ");
            for( int i=0; i<user_input.length(); i++)
            {
            c = user_input.charAt(i);
            
            if(Character.isDigit(c))
            {
                System.out.print(c);
            }     
            }
             
        }  

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!