learningjava
learningjava

Reputation: 59

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;

Upvotes: 3

Views: 3979

Answers (3)

Anuj Garg
Anuj Garg

Reputation: 35

I don't know much about it as I am also a beginner but i think this should work properly

BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
System.out.print ("Enter your details:");//(suppose name and email)
buffer = br.readLine ();
String[] strArray = buffer.split(' ');
//then this strArray contains all the input separately
String name = strArray[0];
String email= strArray[1];

Upvotes: 1

havogt
havogt

Reputation: 2812

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.

Upvotes: 0

GregH
GregH

Reputation: 5459

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!

Upvotes: 3

Related Questions