简体   繁体   中英

How to check if a line is blank, and if so, skip it, using scanner Java

Lets say the lines in a file are:

Code:

String string = input.nextLine();
int index=0;
System.out.println(string);
if(string.contains(" "))
{
    while(string.contains(" "))
    {
       int random = string.indexOf(" ");
       String temp6 = string.substring(index,random);
       ps.print(pig(temp6)+" ");
       int temp8 = temp6.length();
       String temp7 = string.substring(temp8+1,string.length());
       string=temp7;
    }
    ps.print(pig(string));
}
else
{
    ps.println(pig(string));
    //}
}

For input:

Hello

Bob

How would I get scanner to skip the line after Hello? Or how do I remove that blank line?

Look for this

 public static void main(String[] args) throws FileNotFoundException {

    ArrayList<String> list = new ArrayList<>();
    File file = new File("someFileHere.txt");
    Scanner scanner = new Scanner(file);

    String line = "";
    while (scanner.hasNext()) {
        if (!(line = scanner.nextLine()).isEmpty()) {
            list.add(line);
        }
    }
    scanner.close();

    System.out.println(list);
}

And assume that the someFileHere.txt contains:

Hello

Bob

As you mentioned, they store in the list'Hello' and 'Bob' without any blank line.

In case of both an empty line or an empty line with blank spaces , we can use the following code:-

File file = new File("D://testFile.txt");
        Scanner sc;
        try {
            sc = new Scanner(file);
            while(sc.hasNextLine())
            {
                String text = sc.nextLine();
                // remove mulitple empty spaces from the line 
                text = text.replaceAll("[ ]+", " ");
                // check whether the length is greater than 0
                // and it's just not an empty space 
                if(text.length()>0 && !text.equals(" ")) {
                    System.out.println(text);
                }
            }
            sc.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Input is:- Blob

Random

Carrie

Jason

Output:- Blob Random Carrie Jason

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