如何使用scanner Java检查一行是否为空,如果为空,则跳过该行
假设文件中的行是: 代码: 输入:如何使用scanner Java检查一行是否为空,如果为空,则跳过该行,java,string,java.util.scanner,Java,String,Java.util.scanner,假设文件中的行是: 代码: 输入: Hello Bob 我怎样才能让扫描器在打招呼后跳过这一行? 或者如何删除该空行?查找此项 public static void main(String[] args) throws FileNotFoundException { ArrayList<String> list = new ArrayList<>(); File file = new File("someFileHere.txt"); Sc
Hello
Bob
我怎样才能让扫描器在打招呼后跳过这一行?
或者如何删除该空行?查找此项
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);
}
正如您所提到的,它们存储在列表“Hello”和“Bob”中,没有任何空行。查找此项
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);
}
正如您所提到的,它们在列表中存储“Hello”和“Bob”,没有任何空行。如果是空行或带空格的空行,我们可以使用以下代码:-
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();
}
输入为:-
斑点
随机的
嘉莉
杰森
输出:-
斑点
随机的
卡丽
Jason如果一个空行或一个带空格的空行,我们可以使用以下代码:-
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();
}
输入为:-
斑点
随机的
嘉莉
杰森
输出:-
斑点
随机的
卡丽
杰森你现在如何扫描这些线路?你知道如何检查
字符串
是否为空吗?发布你未删节的代码你读过字符串
类的javadoc吗?你现在如何扫描这些行?你知道如何检查<代码>字符串< /代码>是否是空的?在你的unkip代码中,你是否已经阅读了<代码>字符串< /Cord>类'javaDoc?如何不使用数组或数组来删除空白行?你可以使用删除字符串中的新行“\n”来删除空白行而不使用数组或数组吗?删除字符串中的新行“\n”