javaarraysstringbufferedreader

Using BufferedReader to read an array?


I'm just beginning to learn Java, and I'm unsure of how to use BufferedReader to read an array in the assignment I'm working on. getSalesData is its own method. I understand that I need to use BufferedReader to ask the user to input a number (which are Strings here) and then store it in data [0] and [1], but I'm unsure of how to proceed and fix the errors. Any tips would be very much appreciated!

   String [] getSalesData (){
        String [] data = new String [2];
        String [] ticketsSold = "";
        String [] ticketPrice = "";

        BufferedReader br = null;
        String buffer = new String ();

        try {
            br = new BufferedReader (new InputStreamReader(System.in));
            System.out.print ("Enter your agent ID:");
            buffer = br.readLine ();
            ticketsSold = buffer;

            br = new BufferedReader (new InputStreamReader(System.in));
            System.out.print ("Enter your agent ID:");
            buffer = br.readLine ();
            ticketPrice = buffer;


        } catch (Exception e) {
            System.out.println ("Invalid entry");
        }

        return data;

Solution

  • br.readLine() will return a String and you are setting ticketsSold = buffer. So let's examine a little closer: buffer is a string and ticketsSold is an array of strings. this should produce an error for you (if you can post the error stack trace that would be very helpful). I'm not sure if you actually want ticketsSold and ticketPrice to be arrays of Strings as here it looks as if they should just be strings.

    So if you want them to really be arrays of strings, use:

    ticketsSold[0] = buffer;
    

    and

    ticketPrice[0] = buffer;
    

    or you can change the declartion of ticketPrice and ticketsSold to be strings:

    String ticketsSold = "";
    String ticketPrice = "";
    

    hope this helps and welcome to stack overflow!