Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从ArrayList中提取特定的数字?_Java_Tdd - Fatal编程技术网

Java 如何从ArrayList中提取特定的数字?

Java 如何从ArrayList中提取特定的数字?,java,tdd,Java,Tdd,我编写了一个程序,可以从中提取文本数据并提取X,其中X是“unixtime”旁边的值。这就是我目前得到的 public class GetDataService implements DataService{ @Override public ArrayList<String> getData() { ArrayList<String> lines = new ArrayList<>(); try { URL url = ne

我编写了一个程序,可以从中提取文本数据并提取X,其中X是“unixtime”旁边的值。这就是我目前得到的

public class GetDataService implements DataService{
  @Override
  public ArrayList<String> getData()  {
    ArrayList<String> lines = new ArrayList<>();
    try {
    URL url = new URL("http://worldtimeapi.org/api/ip.txt");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    while ((line = bufferedReader.readLine()) != null) {
      String a = line;
      lines.add(a);
      }
      bufferedReader.close();

    } catch (IOException ex) {
      throw new RuntimeException("Can not making the request to the URL.");
    }
    return lines;
  }

public interface DataService {
  ArrayList<String> getData() throws IOException;
}

public class UnixTimeExtractor {
  private GetDataService getDataService;

  public String unixTimeExtractor()  {
    ArrayList<String> lines = getDataService.getData();
//how to extract the value next to "unixtime"
public类GetDataService实现数据服务{
@凌驾
公共ArrayList getData(){
ArrayList行=新的ArrayList();
试一试{
URL=新URL(“http://worldtimeapi.org/api/ip.txt");
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(url.openStream());
弦线;
而((line=bufferedReader.readLine())!=null){
字符串a=行;
行。添加(a);
}
bufferedReader.close();
}捕获(IOEX异常){
抛出新的RuntimeException(“无法向URL发出请求”);
}
回流线;
}
公共接口数据服务{
ArrayList getData()抛出IOException;
}
公共类UnixTimeExtractor{
私有GetDataService GetDataService;
公共字符串unixTimeExtractor(){
ArrayList lines=getDataService.getData();
//如何提取“unixtime”旁边的值

我不知道如何提取“unixtime”旁边的值。我如何测试GetDataService类的网络错误。

您可以使用
indexOf
迭代ArrayList并获取下一个值

public String unixTimeExtractor() {
    List<String> lines = getDataService.getData();

    int i = lines.indexOf(unixTime);

    if (i != -1 && ++i < lines.size()) {
        return lines.get(i);
    }
    return null;
}
公共字符串unixTimeExtractor(){
列表行=getDataService.getData();
int i=lines.indexOf(unixTime);
如果(i!=-1&&++i
我不知道如何提取“unixtime”旁边的值

要从列表中提取值,可以迭代列表, 根据需要对每个值进行检查, 并在找到匹配项时返回值,例如:

for (String line : lines) {
  if (line.startsWith("unixtime: ")) {
    return line;
  }
}
要提取字符串中“unixtime:”后面的值,可以使用以下几种策略:

  • line.substring(“unixtime:.length())
  • line.replaceAll(“^unixtime:”,”)
  • line.split(“:”[1]
顺便问一句,你真的需要这一行的列表吗? 如果没有,那么如果在从URL读取输入流时执行此检查,则可以节省内存并减少输入处理, 当你找到你需要的东西后,立即停止阅读

以及如何测试GetDataService类的网络错误

要测试是否正确处理了网络错误, 您需要使可能引发网络错误的代码部分可注入。 然后在您的测试用例中,您可以注入替换代码来引发异常, 并验证程序是否正确处理异常

一种技术是“提取和扩展”。 也就是说,提取对专用方法的
url.openStream()
调用:

InputStream getInputStream(URL url) throws IOException {
  return url.openStream();
}
并将代码中的
url.openStream()
替换为调用
getInputStream(url)
。 然后在您的测试方法中,您可以通过抛出异常来覆盖此方法, 并验证发生了什么。使用AssertJ的流畅断言:

  @Test
  public void test_unixtime() {
    UnixTimeExtractor extractor = new UnixTimeExtractor() {
      @Override
      InputStream getInputStream(URL url) throws IOException {
        throw new IOException();
      }
    };
    assertThatThrownBy(extractor::unixtime)
      .isInstanceOf(RuntimeException.class)
      .hasMessage("Error while reading from stream");
  }

对于从输入流读取,您也可以执行类似的操作。

您可以使用java-8实现相同的操作。请将您的方法更改为以下方法:

public String unixTimeExtractor() {
   ArrayList<String> lines = getDataService.getData();
   return lines.stream().filter(s -> s.contains("unixtime"))
               .map(s -> s.substring("unixtime: ".length()))
               .findFirst()
               .orElse("Not found");
}
公共字符串unixTimeExtractor(){
ArrayList lines=getDataService.getData();
返回行.stream().filter(s->s.contains(“unixtime”))
.map(s->s.substring(“unixtime:.length()))
.findFirst()
.orElse(“未找到”);
}
在这里,我们对列表
行进行流式处理
以检查是否找到字符串
unixtime
。如果找到,则使用子字符串返回其值,否则返回
未找到


对于测试用例,您可以参考janos的答案。

@minhquango该测试可以使用Mockito实现。如果您在使其工作时遇到困难,您应该单独提出一个问题。请参阅。。。