java - 尽管已声明变量,但无法找到符号 - 变量

标签 java variables methods symbols cannot-find-symbol

在 main 方法中使用 numThrows 变量时,会引发未找到变量的错误。即使我在其中一种方法中声明它。 我在 void 提示方法中使用声明变量。该程序旨在使用随机坐标计算 Pi,然后使用公式根据用户给定的尝试次数来估计饼图。

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 在另一个函数中声明,则其 scope没有扩展到 main 方法。

相反,如果您想在 main 方法和另一个方法中使用它,请将其设为类实例。

例如:

class SomeClass {
    public static int numThrows = 2;
    public static void test() {
        numThrows = 4; // it works!
    }
    public static void main(String[] args) {
        System.out.println(numThrows); // it works!
    }
}

因此,它的作用域将扩展到类的所有成员,而不仅仅是方法。

关于java - 尽管已声明变量,但无法找到符号 - 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34688263/

相关文章:

macos - Apple 是否支持 Java 6?

class - VBA 类方法链接

c# - 如何在 C# 中将属性作为参数传递?

ruby - 在 Ruby 中是否有性能原因更喜欢大小而不是长度或计数?

java - 在 ArrayList<String> 中查找

java - 在服务器端记录 SSL 错误(如 javax.net.debug=ssl)

java - 如何在 Spring MVC 中处理对静态页面的寻址

android - 如何将变量从线程传递到外部环境?

c++ - 在另一个文件中引用 C++ 结构对象?

java - Google App Engine 中的单例可能会过期,或者任何静态变量都会过期吗? ( java )