Rohit Negi
Rohit Negi

Reputation: 435

reading single character in java

public class pattern7 {
    public static void main(String args[])
        throws java.io.IOException{

        char c;

        do
        {
            System.out.print("*");
            System.out.println("\ndo you want more");
            c=(char)System.in.read();
        }while(c=='y');
    }
}

the above code should print the * as long as i press 'y' but it does not do so. it let the user to enter choice just once. i know the reason behind this as it uses "enter" as its second value. but i don't know how to make it work. suggest me the code to do the same action properly

Upvotes: 0

Views: 100

Answers (3)

Bruce
Bruce

Reputation: 8849

it takes enter key press as a new character. So capture that key press add another read command.

    do
    {
        System.out.print("*");
        System.out.println("\ndo you want more");
        do {
            c=(char)System.in.read();
        } while (Character.isWhitespace(c));
    } while (c=='y');

Upvotes: 1

ranjanm28
ranjanm28

Reputation: 99

You can do this by using Scanner. Here is my code-

public class pattern7 {
    public static void main(String args[])
        throws java.io.IOException{

        char c;
        Scanner reader = new Scanner(System.in);
        do
        {
            System.out.print("*");
            System.out.println("\ndo you want more");
            c=reader.next().charAt(0);
        }while(c=='y');
    }
}

Upvotes: 0

WeSt
WeSt

Reputation: 2684

If the 'y' character will always be followed by an enter, just always read the full line and check if it only contains the 'y' character:

Option 1: BufferedReader

You can use InputStreamReader in combination with BufferedReader to get the full line the user entered. After that, you check that it is not null and only contains 'y'.

try {
    // Get the object of DataInputStream
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    String line = "";
    while ((line = br.readLine()) != null && line.equals("y") ) {
        System.out.print("*");
        System.out.println("\ndo you want more?");
    }
    isr.close();
} catch (IOException ioe) {
    ioe.printStackTrace();
} 

Option 2: Scanner

The same as above can be achieved by using the java.util.Scanner class:

Scanner scan = new Scanner(System.in);
scan.nextLine(); // reads a line from the console. Can be used instead of br.readLine();

Upvotes: 0

Related Questions