如何检查行是否为空,如果是,则使用扫描程序Java跳过它

时间:2013-09-25 02:30:28

标签: java string java.util.scanner

让我们说文件中的行是:

代码:

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));
    //}
}

输入:

Hello

Bob

在Hello之后,我如何让扫描仪跳过这条线? 或者如何删除该空白行?

2 个答案:

答案 0 :(得分:3)

寻找这个

 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);
}

并假设someFileHere.txt包含:

Hello

Bob

正如你所提到的,他们存储在列表'你好'和'鲍勃'中没有任何空行。

答案 1 :(得分:0)

如果空行空行带空格,我们可以使用以下代码: -

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();
        }

输入是: - 团块

随机

卡丽

杰森

输出: - 斑点 随机 嘉莉 杰森