该方法应该在行上添加所有整数打印出结果,然后移到下一行。
当我运行该方法时,它会添加除行中最后一个之外的所有整数,除非它后面有空格。无论是否有空格,我怎样才能添加整数呢?
public static void addRows(String fileName) {
int count = 0;
int x;
try {
Scanner s = new Scanner(new File(fileName));
s.useDelimiter("[ ]+");
while (s.hasNext()) {
if (s.hasNextInt()) {
x = s.nextInt();
count += x;
}
else {
System.out.println(count);
count = 0;
s.nextLine();
}
}
System.out.println(count);
}
catch(IOException e) {System.out.println("No File Found.");}
}
Sample Input:
1 2 3
1 2 3
Output:
3
6
答案 0 :(得分:0)
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String input;
while ((input = reader.readLine()) != null) {
int sum = 0;
String[] fields = input.split("\\s");
for (String field : fields) {
try {
sum += Integer.parseInt(field);
} catch (NumberFormatException e) {
// ignored
}
}
System.out.println(sum);
}
答案 1 :(得分:0)
while (true) {
if (s.hasNextInt()) {
count += s.nextInt();
} else if (s.hasNext()) {
next();
} else if (s.hasNextLine()) {
s.nextLine();
} else {
break;
}
}
无论您如何定义分隔符模式以及是否可以忽略换行符,都应该有效。
答案 2 :(得分:0)
一种选择是使用前瞻在行尾注册伪定界符,而不实际使用\ n:
s.useDelimiter("[ ]+|(?=\\n)");
答案 3 :(得分:0)
使用分隔符很难做到这一点。
试试这段代码。我已经测试了它的样本输入。有用。
public static void addRows(String fileName)
{
int count = 0;
int x;
try
{
Scanner s = new Scanner(new File(fileName));
while (s.hasNextLine())
{
String line = s.nextLine(); // get the next line
Scanner lineScanner = new Scanner (line); // get a new scanner for the next line! Done! Now proceed the usual way.
while (lineScanner.hasNextInt())
{
x = lineScanner.nextInt();
count += x;
}
System.out.println(count);
count = 0;
}
}
catch(IOException e)
{
System.out.println("No File Found.");
}
}