gpt4 book ai didi

java - 如何将行值相加

转载 作者:行者123 更新时间:2023-12-01 18:46:13 24 4
gpt4 key购买 nike

在这段java代码中,我试图从read.txt文件中读取每一行,但如果我传递参数,我想获取行号

例如:- read.txt 包含

2
2
4
5
6
7
7
8
8
9

我传递参数9

那么程序应该返回第 10 行

因为我给出的参数值出现在第 10 行 我该怎么做?

这是我尝试过的Java代码:

import java.io.*;

class CountRows
{
public static void main(String args[])
{
setForSum("read.txt",9);
}

public static void setForSum(String filename,int param2)
{
try
{
FileInputStream fstream = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fsteam));
String strLine;
while ((strLine = br.readLine()) != null)
{
System.out.println (strLine);
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

最佳答案

import java.io.*;

class CountRows
{
public static void main(String args[])
{
setForSum("read.txt",9);
}

public static void setForSum(String filename,int param2)
{
try
{
FileInputStream fstream = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int i = 0;
while ((strLine = br.readLine()) != null)
{
i++;
if(param2 == Integer.parseInt(strLine){
//print the i i.e line number
}
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

关于java - 如何将行值相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17693134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com