简体   繁体   English

如何使用扫描仪Java检查行是否为空白,如果是,请跳过该行

[英]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? 在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: 并假设someFileHere.txt包含:

Hello

Bob

As you mentioned, they store in the list'Hello' and 'Bob' without any blank line. 如您所述,它们存储在列表“ Hello”和“ Bob”中,没有任何空白行。

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 输入为:-Blob

Random 随机

Carrie 嘉莉

Jason 杰森

Output:- Blob Random Carrie Jason 输出:-Blob Random Carrie Jason

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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