Durgaprasad
Durgaprasad

Reputation: 157

readLine() does not work properly

i have problem with readLine() ,i.e, my system does not accept my any input request and its directly execute the next line what is the wrong in my code my code is:

System.out.println("Choose your option:\n"
                + "To Add   :\tA/a\n"
                + "To Delete:\tD/d\n"
                + "To Update:\tu/U\n"
                + "To Exit  :\tpress any key");
        char ch = (char) br.read();
        //br.readLine().charAt(0);
        br.skip(1);
        if(ch =='a' || ch == 'A'){
           addElement();
        }
        else if(ch == 'd' || ch == 'D') {
            System.out.println("Please enter emp id :");
            int id = Integer.parseInt(br.readLine());
            //int id = Integer.parseInt(System.console().readLine("enter emp"));
            deleteElement(id);
        }
        else if(ch == 'u' || ch == 'U') {
            System.out.println("Please enter emp id :");
            int id = Integer.parseInt(br.readLine());
            updateElement(id);
        }
        else System.exit(0);

this code is working in only netbeans command mode it is not accessible thanks

Upvotes: 0

Views: 2959

Answers (2)

sudhan
sudhan

Reputation: 1

Try this if you are getting input through cmd line(Terminal)

String emp = System.console().readLine("Please enter emp name");

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500185

The problem is that the first character read here:

char ch = (char) br.read();

... won't be available until you've hit return, at which point you've got an empty line.

If you run your code and type

dSomeone

(and then hit return) then you'll get a name of "Someone" to try to delete.

The simplest approach would probably be to use:

String option = br.readLine();
if (option == null) {
    // User has basically terminated stdin. Die somehow
}

if (option.equalsIgnoreCase("D")) {
    String name = br.readLine();
    ...
}

Also note that this code isn't useful:

String empName = br.readLine();
deleteElement();

You're asking for a name, but then ignoring it. How is deleteElement meant to know which employee you want to delete? You should probably make the name a parameter to the method, and supply it when calling:

String empName = br.readLine();
deleteElement(empName);

Upvotes: 2

Related Questions