How do i input a string from a buffered reader?

OVERTONE picture OVERTONE · Dec 2, 2009 · Viewed 21.3k times · Source

Im used too using Scanner mainly and want too try using a buffered reader: heres what i have so far

import java.util.*;
import java.io.*;
public class IceCreamCone 
{
// variables
String flavour;
int numScoops;
Scanner flavourIceCream = new Scanner(System.in);

// constructor
public IceCreamCone()
{

}
// methods
public String getFlavour() throws IOexception 
{
    try{

    BufferedReader keyboardInput;
    keyboardInput = new BufferedReader(new InputStreamReader(System.in));
    System.out.println(" please enter your flavour ice cream");
    flavour  =  keyboardInput.readLine();
    return keyboardInput.readLine();
    }
    catch (IOexception e)
    {
        e.printStackTrace();
    }
}

im fairly sure to get an int you can say

Integer.parseInt(keyboardInput.readLine());

but what do i do if i want a String

Answer

bruno conde picture bruno conde · Dec 2, 2009

keyboardInput.readLine() already returns a string so you should simply do:

return keyboardInput.readLine();

(update)

The readLine method throws an IOException. You either throw the exception:

public String getFlavour() throws IOException {
   ...
}

or you handle it in your method.

public static String getFlavour() {
    BufferedReader keyboardInput = null;
    try {
        keyboardInput = new BufferedReader(new InputStreamReader(System.in));
        System.out.println(" please enter your flavour ice cream");
        // in this case, you don't need to declare this extra variable
        // String flavour = keyboardInput.readLine();
        // return flavour;
        return keyboardInput.readLine();
    } catch (IOException e) {
        // handle this
        e.printStackTrace();
    }
    return null;
}