0

I have a string with multiple line, I want to display them individually example when I only want to display the first inline it will show only 'apple'

Example display line 1 = orange

What i haven done is as follows, it can display all but unable to select which fruit position to display

   public static void main(String args[]) {


        String fruit = "apple" + "\n" + "orange"+"\n"+"pear";

        BufferedReader br = null;
        try {
            String sCurrentLine;
            br = new BufferedReader(new StringReader(fruit));
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

output: 
apple
orange
pear

1 Answer 1

4

Try using String#split instead, for example...

String fruit = "apple" + "\n" + "orange"+"\n"+"pear";
String[] basket = fruit.split("\n");

This will allow you to access each element individually by index

Sign up to request clarification or add additional context in comments.

4 Comments

I have done the same thing before which is reading from file, but now i try to read from a string instead
@user2822351 Okay, and the difference being?
haha I dont know as it didnt show Stringreader can use split, it wasnt stated in the book
split can be used with any String, it's a method of the String class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.