如何在Java中运行循环?

时间:2019-02-12 06:00:22

标签: java

我想知道为什么此代码无法运行。缺少什么吗?

计算给定字符串中"xx"的数目。我们将说允许重叠,因此"xxx"包含2个"xx"

public class Drumkit {
    int countXX(String str){
        String a = "abcxxx";
        int count = 0;
        for (int i = 0; i < str.length() - 1; i++) {
            if (a.substring(i, i + 2).equals("xx")) count++;
        }
        return count;
    }
}

2 个答案:

答案 0 :(得分:0)

您正在传递str,并在函数中使用其length()。但是,在循环中,您使用的是a(本地字符串变量),这似乎是一个逻辑错误。

调用此函数时,需要传递输入字符串,并使用str(函数参数)来计算匹配项。

这是一个实用的示例:

class Test
{
    static int countXX( final String str ) {
        int count = 0;
        for (int i = 0; i < str.length() - 1; i++) {
            if (str.substring(i, i + 2).equals("xx")) count++;
        }
        return count;
    }

    public static void main (String[] args)
    {
        final String s = "abcxxx";
        final int count = countXX( s );
        System.out.println( count );
    }
}

这是实时示例:https://ideone.com/Lm6Ir4

答案 1 :(得分:0)

您的问题尚不清楚。但是,您可以尝试使用此代码

<?php

//Send the mail

// Require the bundled autoload file - the path may need to change
// based on where you downloaded and unzipped the SDK
require __DIR__ . '/Twilio/autoload.php';


// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$sid = xxxxx
$token = xxxx
$client = new Client($sid, $token);

    $client->messages->create(
        $to,
        array(
            'from' => $from,
            'body' => "Thanks for eaching out again",
        )
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>