java.lang.StringIndexOutOfBoundsException

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rkdesign
    New Member
    • May 2010
    • 1

    java.lang.StringIndexOutOfBoundsException

    i am new to java
    i am entering some data run time. like emp details
    problem is char type
    if i entered sex = m program will be terminated. exception is java.lang.Strin gIndexOutOfBoun dsException.
    if i entered sex = male (enter key)
    program executed successfully . but problem is i can't entered next command line arguments . program will display result empty values

    This is my Program
    Code:
    import java.io.*;
    
    class str2
    {
    	public static void main(String args[]) throws IOException
    	{
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		
    		System.out.print("Enter Employee ID = ");
    		int id = Integer.parseInt(br.readLine());		
    		
    		System.out.print("Enter Genger(M/F) : ");
    		char sex = (char)br.read();
    		br.readLine().charAt(0);
    		br.skip(2);
    		
    		System.out.print("Enter Employee Name = ");
    		String name = br.readLine();
    
    		System.out.println("Employee Name = " + name);
    		System.out.println("Employee ID = " + id);
    		System.out.println("Employee Gender = " + sex);
    	}
    
    }
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Why do you use
    br.readLine().c harAt(0);
    as opposed to just
    br.readLine();
    ??
    You aren't doing anything with the character, and are just causing problems for yourself. Also, get rid of the br.skip(2);

    ===
    A better way to get the line would be something like
    Code:
    do{
     String line = readLine()
    } while ! line.equals("");
    sex = line.charAt(0); // will work because we know line isn't empty.

    Comment

    Working...