CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 1999
    Posts
    2

    Need Help Reading Data Entered From Keyboard

    Help!!

    What seems like an easy problem, seems very hard to me. I can't quite figure out how to read an integer, string, or double, etc.

    I send a message prompting the user to enter their age for example. How do I read the value in?

    Thanks in advance,

    Lonnie


  2. #2
    Join Date
    Sep 1999
    Location
    Madurai , TamilNadu , INDIA
    Posts
    1,024

    Re: Need Help Reading Data Entered From Keyboard


    Sample program ...



    import java.io.*;

    public class ReadFromConsole{

    public static void main( String[] str ){
    Person p = new Person();
    p.getData();
    p.displayData();
    }
    }

    class Person{

    private String m_strName;
    private int nWeight;

    private BufferedReader reader;

    public Person(){
    try{
    // This reader is going to read the data from the console.
    reader = new BufferedReader( new InputStreamReader( System.in ) );
    }catch( Exception e ){}
    }


    public void getData(){
    try{
    do{
    System.out.print( "Enter Name : " );
    m_strName = reader.readLine(); // This will read the entered data from the console
    }while( ( m_strName == null ) || ( m_strName.trim().length() == 0 ) );


    String weight = null;
    do{
    System.out.print( "Enter Weight in Pounds : " );
    weight = reader.readLine();
    if( !checkInt( weight )){
    weight = null;
    }
    }while((weight == null ) || ( weight.trim().length() == 0 ));

    // Convert String to Int.
    nWeight = Integer.parseInt( weight );

    }catch( Exception e ){}
    }

    public void displayData(){
    System.out.println("Your name is : " + m_strName );
    System.out.println("Your weight is : " + nWeight );
    }


    private boolean checkInt(String strInput){
    for( int i = 0; i < strInput.length() ; i++ ){
    char ch = strInput.charAt(i);
    if( !Character.isDigit(ch)){
    return false;
    }
    }
    return true;
    }
    }





Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured