尽管已声明变量,但找不到符号-变量 [英] Cannot find Symbol - Variable, despite the variable being declared
问题描述
numThrows变量引发在主方法中使用时找不到的变量错误.即使我在其中一种方法中声明了它. 我在void提示方法中使用了声明变量.该程序旨在使用随机坐标计算Pi,然后使用公式来估算用户给定尝试次数下的饼图.
The numThrows Variable is inciting an error of variable not found when used in the main method. even though i declare it in one of the methods. I use the declare the variable in the void prompt method. This program is designed to calculate Pi using random coordinates then uses a formula to estimate pie over a user given amount of tries.
import java.util.Random;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
public class Darts
public static void prompt()
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
}
public static double[] randomX( int numThrows)
{
int darts = 0;
int i = 0;
double[] cordX = new double[numThrows];
while(darts <= numThrows)
{
cordX[i] = Math.random();
i++;
}
return cordX;
}
public static double[]randomY(int numThrows)
{
int darts = 0;
int i = 0;
double [] cordY = new double[numThrows];
while(darts <= numThrows)
{
cordY[i] = Math.random();
i++;
}
return cordY;
}
public static void getHits(int numThrows, double[] cordX, double[] cordY)
{
int ii = 0;
int i = 0;
double hits = 0;
double misses = 0;
for(i = 0; i <= numThrows; i++)
{
if( Math.pow(cordX[ii],2) + Math.pow(cordY[ii],2) <= 1)
{
hits++;
ii++;
}
else{
misses++;
}
}
}
public static double calcPi(int misses, int hits)
{
int total = hits + misses;
double pi = 4 * (hits / total);
}
// public static void print(double pi, int numThrows)
// {
// System.out.printf(" %-7s %3.1f %7s\n", "Trial[//numtrial]: pi = "
// }
public static void main(String[] args)throws IOException
{
prompt();
double[] cordX = randomX(numThrows);
double[] cordY = randomY(numThrows);
gethits();
double pi = calcPi(misses, hits);
}
}
推荐答案
numThrows是提示方法的实例变量.如果您想做我想做的事,请使numThrows在任何方法之外成为一个静态变量.
numThrows is an instance variable to your prompt method. If you want to do what I think you want to do, make numThrows a static variable outside any methods.
它看起来像这样:
public class Darts {
public static int numThrows
public static int numTrials
可以从任何方法中引用这些变量.这应该可以解决.
These variables can be referenced from any method. This should fix it.
这篇关于尽管已声明变量,但找不到符号-变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!