我有file
,其中包含以下内容:
5
Derrick Rose
1 15 19 26 33 46
Kobe Bryant
17 19 33 34 46 47
Pau Gasol
1 4 9 16 25 36
Kevin Durant
17 19 34 46 47 48
LeBron James
5 10 17 19 34 47
每个名称和数字之间有一个空行。但是当我使用nextLine()扫描文件时;方法我得到以下内容:
NAME:
NAME:
NAME: Derrick Rose
NAME:
NAME: 1 15 19 26 33 46
NAME:
NAME: Kobe Bryant
NAME:
NAME: 17 19 33 34 46 47
NAME:
有人能告诉我我的代码中出现问题的位置以及扫描空行的原因。
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++)
{
String name = scan.nextLine();
System.out.println("NAME: " + name);
}
答案 0 :(得分:4)
似乎你想忽略空行,你可以只检查你要写入控制台的行的长度。它不可能不扫描空行,您至少需要跳过它们才能进一步潜入流中。
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++) {
String name = scan.nextLine();
if (name.trim().length() > 0)
System.out.println("NAME: " + name);
}
答案 1 :(得分:3)
如果您的输入中有换行符,则会消耗一次scan.NextLine()
的调用,因为该函数会在换行符上划分。如果你想要它忽略空白行,那么你应该明确地检查它们,然后如果这些行不是空白则显式增加你的计数器。
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); )
{
String name = scan.nextLine();
if (!name.trim().equals("")) i++;
System.out.println("NAME: " + name);
}
答案 2 :(得分:1)
您可以检查空白行并忽略它们。下面的代码应该这样做。
Scanner scan = new Scanner(file);
int lim = scan.nextInt();
for(int i = 0; i < (lim * 2); i++)
{
String name = scan.nextLine();
if (!name.equals("")){
System.out.println("NAME: " + name);
}
}
答案 3 :(得分:0)
以下类ExcludeEmptyLines.java工作
package com.stackoverflow.java.scannertest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* Created by fixworld.net on 03-September-2015.
*/
public class ExcludeEmptyLines {
public static void main(final String[] args)
throws FileNotFoundException {
String dataFileFullPath = "<replace with full path to input file>";
File inputFile = new File(dataFileFullPath);
Scanner scan = new Scanner(inputFile);
int numEntries = scan.nextInt();
System.out.println("NumEntries = " + numEntries);
for(int i = 0; i <= (numEntries * 4); i++)
{
String inputLine = scan.nextLine();
if(!inputLine.trim().equalsIgnoreCase("")) {
System.out.println("inputLine = " + inputLine);
}
}
}
}
运行它的输出是
NumEntries = 5
inputLine = Derrick Rose
inputLine = 1 15 19 26 33 46
inputLine = Kobe Bryant
inputLine = 17 19 33 34 46 47
inputLine = Pau Gasol
inputLine = 1 4 9 16 25 36
inputLine = Kevin Durant
inputLine = 17 19 34 46 47 48
inputLine = LeBron James
inputLine = 5 10 17 19 34 47