让我们说文件中的行是:
代码:
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之后,我如何让扫描仪跳过这条线? 或者如何删除该空白行?
答案 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();
}
输入是: - 团块
随机
卡丽
杰森
输出: - 斑点 随机 嘉莉 杰森