idn
idn

Reputation: 33

How can i read a multiple line text in java with space between lines

i want to read those 3 lines in an ArrayList of Strings and my code is nod adding something in my ArrayList. Input:

1,1,1,1,0,1,1,0

0,1,1,0,0,1,1,1

1,1,1,1,1,1,1,0

Segm.java:

import java.util.*;
public class Segm 
{
    public static void main(String[] args) 
    {
        Scanner scan=new Scanner(System.in);
        ArrayList<String> s=new ArrayList();
        while(scan.hasNextLine())
        {
            String a=scan.nextLine();
            if(a.isEmpty())
            {
                scan.nextLine();
            }
            s.add(a);
        }
    }
}

Upvotes: 1

Views: 284

Answers (4)

Joakim Danielson
Joakim Danielson

Reputation: 52068

Here is how would do it. Ignore empty lines and exit if user inputs a q

Scanner scan = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<>();
while(scan.hasNextLine()) {
    String a = scan.nextLine();
    if (a.trim().isEmpty()) {
         continue;
    }
    if (a.equalsIgnoreCase("Q")) {
        break;
    }
   strings.add(a);
}

Upvotes: 0

Kaderson
Kaderson

Reputation: 1

   Scanner scan =new Scanner(System.in);
    ArrayList<String> s=new ArrayList();
    while(scan.hasNextLine())
    {
        String a=scan.nextLine();

        if(a.equals("fine"))
            break;
        if(!a.isEmpty())
        {
        s.add(a);

        }
    }

Upvotes: 0

camickr
camickr

Reputation: 324197

I would do something like:

while(scan.hasNextLine())
{
    String a=scan.nextLine();
    if( !a.isEmpty())
    {
        s.add(a);
    }
}

That is, don't assume there is only a single blank line. The above code will ignore all blank lines.

Upvotes: 3

mettleap
mettleap

Reputation: 1410

You are not assigning the a variable again in the subsequent call to nextLine(),

String a=scan.nextLine();
if(a.isEmpty())
{
    a=scan.nextLine(); // you are doing scan.nextLine(); only and not updating a
}
s.add(a);

Also, to handle multiple empty lines, you should consider using a while loop instead of an if statement block in your code

Upvotes: 0

Related Questions