Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.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 用leibiniz序列计算第n项的pi_Java_Eclipse - Fatal编程技术网

Java 用leibiniz序列计算第n项的pi

Java 用leibiniz序列计算第n项的pi,java,eclipse,Java,Eclipse,嘿,我必须创建一个方法,在这个方法中,我必须使用leibiniz序列计算传递项a的π。这就是我目前所拥有的 public static double calculatePi(int a){ double oddNum=1; double pi=0; for(int x=0; x<a; x++){ if(x%2==0) pi=pi+(4/oddNum); else pi=pi-(4

嘿,我必须创建一个方法,在这个方法中,我必须使用leibiniz序列计算传递项a的π。这就是我目前所拥有的

public static double calculatePi(int a){
    double oddNum=1;
    double pi=0;
    for(int x=0; x<a; x++){
        if(x%2==0)
            pi=pi+(4/oddNum);
        else
                pi=pi-(4/oddNum);
        oddNum=oddNum+2;
    }
return pi;
}
我还需要帮助编写一个接受传递的字符串和xterm的方法。在该方法中,它将每x个字母添加一个字母。因此,如果它通过圣代,2它将返回圣代。我已经记下了它的大部分,但是有一个逻辑错误,不允许像cats,3这样的东西编译

public static String addPounds(String s, int x){
    String a="";
    for(int i=0; i<s.length(); i=i+x){
        a=(a+s.substring(i,i+x)+"#");
    }
    return a;
}

非常感谢

您的addPounds方法对给定的示例cats抛出StringIndexOutOfBoundsException,3

for(int i=0; i<s.length(); i=i+x){
    a=(a+s.substring(i,i+x)+"#");
}
在这个for循环的第一次执行中,变量“a”将正确地为Cat。但现在它出了问题。 变量“i”增加到3。现在你想得到一个子串,从索引3开始,以索引6结束。字符串Cats只有4个字母,因此IndexOutOfBoundsException

我想解决问题的最简单方法是插入一个if-else语句,如下所示:

for(int i=0; i<s.length(); i=i+x){
        if(s.length()>=i+x){
            a=(a+s.substring(i,i+x)+"#");
        }
        else{
            a= a+s.substring(i);
        }
    }

你的pi方法很好用

你应该把另一个换成这个。我写的有点不同,所以你很容易理解逻辑

public static String addPounds(String s, int x){
    String a = "";

    //starting from 1 so i can do mod division easily
    for(int i = 1; i <= s.length(); i++){

        //check if next # has to be placed at the end
        if(i + 1 > s.length() && (i + 1) % x == 0){
            a += "#";

        //check if next # has to be placed somewhere inside the string
        }else if(i % x == 0){
            a += s.charAt(i - 1);
            a += "#";

        //oherwise just add the char at i-1
        }else {
            a += s.charAt(i - 1 );

        }
    }
    return a;
}