2013-09-25 69 views
0

可以說,在一個文件中的線路有:如何檢查是否一行是空白的,如果有,跳過它,使用掃描儀的Java

代碼:

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 

我怎麼會讓掃描儀跳過後你好? 或者我如何刪除空行?

+1

你現在怎樣掃描線條?你知道如何檢查'String'是否爲空? –

+1

發佈你的unskiped代碼 – newuser

+0

你讀過'String'類的javadoc嗎? –

回答

2

尋找此

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 

正如你所說,他們在list'Hello」和 '鮑勃' 存儲沒有任何空行。

+0

如何在不使用ArrayList或數組的情況下刪除空行? –

+0

您可以使用[正則表達式](http://stackoverflow.com/questions/4123385/remove-all-empty-lines)刪除字符串中的新行'\ n' – Husam