0

假设文件中的行是:

代码:

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 之后如何让扫描仪跳过线路?或者我如何删除那个空行?

4

2 回答 2

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

正如您所提到的,它们存储在列表中的“Hello”和“Bob”中,没有任何空行。

于 2013-09-25T02:46:11.843 回答
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();
        }

输入是:- Blob

随机的

嘉莉

杰森

输出:- Blob Random Carrie Jason

于 2018-04-28T08:05:38.613 回答