I am supposed to add the distance of a walker's position after N steps. I run the while T times and need to add all of the N steps after T trails and divide by the amount of trials to get an average. This is my code so far. Iv tried doing a different integer like distance/T but it says that distance isn't found. Is that because it is defined in the while loop. I am using processing.
import javax.swing.JOptionPane;
String input=JOptionPane.showInputDialog("Steps");
int x=Integer.parseInt(input);
if (x<0)
{
System.out.println("Error. Invalid Entry.");
}
int T=1;
int N=0;
while (T<10)
{
while (N<x)
{
int stepsX=Math.round(random(1,10));
int stepsY=Math.round(random(1,10));
System.out.println(stepsX+","+stepsY);
N=N+1;
if (N==x)
{
int distance=(stepsX*stepsX)+(stepsY*stepsY);
System.out.println(distance);
}
}
T=T+1;
N=0;
}
System.out.println("mean sq. dist = ");
I'm assuming it's because you're not keeping track of total distance. Also, your distance
int variable only exists in the scope:
if (N==x)
{
int distance=(stepsX*stepsX)+(stepsY*stepsY);
System.out.println(distance);
}
Read more about scopes here: Scope of do-while loop?
It's kind of unclear what you need, but here is some changes I made that I think will help:
import javax.swing.JOptionPane;
String input=JOptionPane.showInputDialog("Steps");
int x=Integer.parseInt(input);
if (x<0)
{
System.out.println("Error. Invalid Entry.");
}
int T=1;
int N=0;
double totalDistance = 0.0;//keep track over over distance;
while (T<10)
{
while (N<x)
{
int stepsX=Math.round(random(1,10));
int stepsY=Math.round(random(1,10));
System.out.println(stepsX+","+stepsY);
N=N+1;
if (N==x)
{
int distance=(stepsX*stepsX)+(stepsY*stepsY);
totalDistance = totalDistance + distance;
System.out.println("current distance: " + distance);
System.out.println("current total distance: " + totalDistance);
}
}
T=T+1;
N=0;
}
//calculate whatever you need using totalDistance
System.out.println("mean sq. dist = " + (totalDistance/T) );
This would be my answer, you seem to be loosing all of your steps except last one in a while loop.
import javax.swing.JOptionPane;
String input=JOptionPane.showInputDialog("Steps");
int x=Integer.parseInt(input);
if (x<0)
{
System.out.println("Error. Invalid Entry.");
}
int T=1;
int N=0;
int stepsX = 0;
int stepsY = 0;
while (T<10)
{
while (N<x)
{
stepsX += Math.round(random(1,10));
stepsY += Math.round(random(1,10));
System.out.println(stepsX+","+stepsY);
N=N+1;
if (N==x)
{
int distance=(stepsX*stepsX)+(stepsY*stepsY);
System.out.println(distance);
}
}
T=T+1;
N=0;
}
double distance = Math.sqrt(Math.pow(stepsX, 2) + Math.pow(stepsY, 2));
System.out.println("mean sq. dist = "+distance);
But please if it is not rephrase your question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.