Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.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 通过输入将整个程序运行一定次数_Java_While Loop_Random Walk - Fatal编程技术网

Java 通过输入将整个程序运行一定次数

Java 通过输入将整个程序运行一定次数,java,while-loop,random-walk,Java,While Loop,Random Walk,因此,我当前的代码有效地运行了“随机行走”问题,然后使用毕达哥拉斯定理计算出以行走单位表示的实际距离,但现在我需要修改我的程序,以便对所述行走进行一定数量的试验,然后计算均方距离。不只是寻找答案,我还需要一个解释,这样我就可以学习和重新创建,我想我只需要另一个while循环,但我不知道该放在哪里 import javax.swing.JOptionPane; String a = JOptionPane.showInputDialog("Enter # of footsteps."); int

因此,我当前的代码有效地运行了“随机行走”问题,然后使用毕达哥拉斯定理计算出以行走单位表示的实际距离,但现在我需要修改我的程序,以便对所述行走进行一定数量的试验,然后计算均方距离。不只是寻找答案,我还需要一个解释,这样我就可以学习和重新创建,我想我只需要另一个while循环,但我不知道该放在哪里

import javax.swing.JOptionPane;
String a = JOptionPane.showInputDialog("Enter # of footsteps."); 
int z = Integer.valueOf(a);
int x= 0; // starting x position
int y= 0; // starting y position
double r;
int counterZ = 0;
if (z < counterZ ){
    System.out.println("Error");
}
while ( z > counterZ){
    r=Math.random();

    if (r<0.25){
        x=x+1;
    }

    else if(r > .25 && r<0.50){
        x=x-1;
    }
        else if(r > .5 && r<0.75){ 
        y=y+1;
    }

    else{
        y=y-1;
    }
    counterZ = counterZ + 1;
    System.out.println("(" + x + "," + y + ")");

}
System.out.println("distance = " + round(sqrt((x*x)+(y*y))));
import javax.swing.JOptionPane;
字符串a=JOptionPane.showInputDialog(“输入#个足迹”);
int z=整数。值(a);
int x=0;//起始x位置
int y=0;//起始y位置
双r;
int计数器z=0;
if(zcounterZ){
r=数学随机();

如果(r.25&&r.5&&r,我建议从整齐缩进代码开始,这样代码更容易理解


为了直接回答您的问题,我建议修改程序,使程序的实质内容嵌入到一个方法中(您可以称之为
randomWalk()
),而
main()
方法只调用
randomWalk()
,并执行I/O。这样做之后,修改
main()将非常容易
调用的方法
randomWalk()
while
while循环内多次。

请纠正我的错误,我的理解是,您希望运行步行循环一定次数,并根据循环距离的总和计算平均步行距离。如果是这样,那么您所要做的就是

int noc = Integer.valueOf(JOptionPane.showInputDialog("Enter # of cycles: "));
String a = JOptionPane.showInputDialog("Enter # of footsteps."); 
int z = Integer.valueOf(a);
int sum = 0;
double avg = 0.0;

for(int i=0;i<noc;i++) {
   sum+= randomWalk(z);
}
avg=(double)sum/noc;
System.out.println("the average distance walked in "+ noc + "cycles is "+avg);

您还错过了使用这些类调用
round()
sqrt()
方法
Math
。我已将它们更正为
Math.round()
Math.sqrt()
。如果没有类名,您将得到一个编译器错误,如
找不到Symbol
。我还假设您已将
java.lang.Math
类导入到您的程序中。

很抱歉,我是一名本科学生,对java非常陌生。我对方法一无所知,我想下周我将学习它们,并且我正在使用处理,所以我到目前为止还不需要输入一个。你能帮我构造一个方法吗?@dylnard:你最好等到你在课堂上学习一些关于方法的知识。不过,如果你赶时间,你可以从网上开始。
public static int randomWalk(int z) {
    //place your code here, starting from the `int x=0;`
    //at last instead of printing the distance walked use the following code
    return (int) Math.round(Math.sqrt((x*x)+(y*y)));
}