Lonnie Goldman
October 10th, 1999, 03:50 PM
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
poochi
October 10th, 1999, 04:17 PM
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;
}
}