Home > DeveloperSection > Forums > Taking a string and printing only the digits
Samuel Fernandes
Samuel Fernandes

Total Post:154

Points:1082
Posted on    April-29-2015 1:08 AM

 Java Java 
Ratings:


 1 Reply(s)
 497  View(s)
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


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    April-29-2015 7:37 AM

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);
        }     
        }
         
    }  


Don't want to miss updates? Please click the below button!

Follow MindStick