简体   繁体   中英

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;

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!

peggy's answer already explained why you get the errors and how to resolve them. But actually you don't need ticketsSold and ticketPrice at all. You said you want to put the input in data[0] and data[1] . Therefore, completely remove ticketsSold and ticketPrice and write

data[0] = buffer;

and

data[1] = buffer;

in the appropriate locations. Then your return value will be correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM