[英]Read in integers from a file
該方法應該將行上的所有整數相加,以打印出結果,然后移至下一行。
當我運行該方法時,它將添加除行中最后一個整數以外的所有整數,除非它后面有空格。 無論是否存在空格,如何使它添加整數?
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
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);
}
while (true) {
if (s.hasNextInt()) {
count += s.nextInt();
} else if (s.hasNext()) {
next();
} else if (s.hasNextLine()) {
s.nextLine();
} else {
break;
}
}
無論您如何定義定界符模式以及換行符是否可忽略,它都應該起作用。
一種選擇是在行的末尾使用前瞻方式注冊偽造的分隔符,而實際上不消耗\\ n:
s.useDelimiter("[ ]+|(?=\\n)");
使用定界符很難做到這一點。
嘗試這段代碼。 我已經對其進行了示例輸入測試。 有用。
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.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.