Cannot find Symbol - Variable, despite the variable being declared - java

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);
}
}

If numThrows is declared within another function, then its scope does not extend to the main method.
Instead, if you want to use it in both the main method and the other one, make it a class instance.
For example:
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!
}
}
Therefore, its scope will be extended to all the members of the class, not just the method.

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.
It will look like this:
public class Darts {
public static int numThrows
public static int numTrials
These variables can be referenced from any method. This should fix it.

Try to remove the method prompt() it's unused, and put his block in the main method.
public static void main(String[] args)throws IOException
{
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();
double[] cordX = randomX(numThrows);
...

Related

Beginner Using OOP in java how do I getAverage and getStandardDeviation()

Here's what I have so far from my code. this is an introductory course so we haven't covered more advanced topics yet. With what I gave so far I input number and press -1 but the program doesn't do anything.
WE HAVEN'T COVERED ARRAYS YET.
import java.util.Scanner;
public class DataSet {
private double value,count,sum, sumOfSquares, average;
public DataSet(double value)
{
this.value=value;
}
public double getAverage(){
int value=0;
int count=0;
double sum=0;
while(value != -1){
sum=sum+value;
average=sum/count;
}
return average;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a numbers to get average and standard deviation: ");
int value=input.nextInt();
DataSet s= new DataSet(value);
System.out.println(s.getAverage());
}
}
Try this below program. This class has only average method. You can add any number methods operating on values arraylist.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class DataSet {
private List<Integer> values;
public DataSet(List<Integer> values) {
this.values = values;
}
public double getAverage() {
int sum = 0;
double result = 0.0;
for (int value : values) {
sum = sum + value;
}
if (values.size() > 0) {
result = sum / values.size();
}
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> values = new ArrayList<Integer>();
System.out
.print("Enter a numbers to get average and standard deviation: ");
int value = input.nextInt();
while (value != -1) {
values.add(value);
value = input.nextInt();
}
DataSet s = new DataSet(values);
System.out.println(s.getAverage());
}
}

My code for finding factorial is not working. Please somebody find the error

Here is my code:
It is not working for greater numbers to find factorial using recursion
import java.util.*;
import java.lang.*;
class Main
{
static String fib(int f)
{
if(f!=1)
return ""+(f*(Integer.parseInt(fib(f-1))));
else
return "1";
}
public static void main(String[] args) throws java.lang.Exception
{
Scanner sc= new Scanner(System.in);
int f= sc.nextInt();
int a[]=new int[f];
int i;
for( i=0;i<f;i++)
a[i]=sc.nextInt();
for( i=0;i<f;i++)
System.out.println(fib(a[i]));
}
}
It's a problem of the range of the type integer (2147483647). If you just replace int with long (range 9223372036854775807) like this
import java.util.*;
class Main
{
static String fib(long f)
{
if(f!=1)
return ""+(f*(Long.parseLong(fib(f-1))));
else
return "1";
}
public static void main(String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int f = sc.nextInt();
long a[] = new long[f];
int i;
for(i = 0; i<f; i++)
a[i] = sc.nextLong();
for(i = 0; i<f; i++)
System.out.println(fib(a[i]));
}
}
then the program can already calculate everything under 21!. But if you use double then it should work with higher numbers, because double has a range of 1.7976931348623157E308. With double the max working factorial calculation is 170!.
PS: I'm German so if i wrote incorrect english i'm sorry
There is no error in the logic of your code. Since you use int, whose range is shorter than the factorial of numbers beyond 25, you get faulty output. Instead, use long or, more preferably, BigInteger.
NOTE: You have to import the java.math package that contains the BigInteger class to use this type.
static BigInteger fib(BigInteger f) {
if (!f.equals(BigInteger.ONE))
return f.multiply(fib(f.subtract(BigInteger.ONE)));
else
return BigInteger.ONE;
}
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
int f = sc.nextInt();
int a[] = new int[f];
int i;
for (i = 0; i < f; i++)
a[i] = sc.nextInt();
for (i = 0; i < f; i++)
System.out.println(fib(new BigInteger(String.valueOf(a[i]))));
}
}

How to get the value of method in java?

I want the output from the code that 5=0101 if 1 occur double and add and if 0 occur only double from the algo
Step 1: randomly select an integer s
Step 2: compute the bit length Ls of s
Step 3: compute L=n/Ls, Lr = n%Ls, Sr= s>> (Ls-Lr)
Step 4: if (Lr=0) then compute M=sP Else compute M=sP and Mr=SrP
Step 5: Q= Mr
Step 6: for i=0 to L
6.1 Q=2LsQ
6.2 Q=Q+M
Step 7: return Q
but this program doesn't return any output.
whats wrong with the code, please rectify the error.
Thanks in advance
package main;
import java.awt.Point;
import java.util.Random;
import java.util.Scanner;
public class a {
private static final double M = 0;
static Object Q;
public static double a() {
//public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("enter the no.:");
int k = reader.nextInt();
String str = java.lang.integer.toBinaryString(k);
int n = str.length();
Point P = new Point();
Random r = new Random();
int s = r.nextInt(50) + 1;
int Ls = Integer.toBinaryString(s).length();
int L = n/Ls;
int Lr = n%Ls;
int Sr = s>>(Ls-Lr);
int Mr = 0;
double Q = Mr;
for (int i = 0; i<L; i++) {
Q = (Math.pow(2, Ls)*Q);
//int M;
Q = Q + M;
}
return Q;
}
public void Q() {
// TODO Auto-generated method stub
}
}
Main method
package main;
import main.a;
public class newmeth {
//private static final int Q = 0;
//private static final String SrP = null;
//private static final int M = 0;
//public int Q() {
public static void main(String [] args) {
System.out.println("enter the no.:");
a myjava = new a();
myjava.Q();
Object Q = null;
a(Q);
}
public static int ya(Object Q) {
//System.out.println("enter the no.:");
return 0;
}
}
If I will simplify your code and remove all unused variables - I will get something like that. and as you can see - you are not execute a() method from main()
package main;
import java.util.Random;
import java.util.Scanner;
import static java.lang.Integer.toBinaryString;
public class newmeth {
private static final double M = 0;
public static void main(String[] args) {
System.out.println("enter the no.:");
}
private static double a() {
Scanner reader = new Scanner(System.in);
System.out.println("enter the no.:");
int k = reader.nextInt();
int n = toBinaryString(k).length();
int s = new Random().nextInt(50) + 1;
int Ls = toBinaryString(s).length();
int L = n / Ls;
double Q = 0;
for (int i = 0; i < L; i++)
Q = (Math.pow(2, Ls) * Q) + M;
return Q;
}
}
And minimal useful changes is change main method like below
public static void main(String[] args) {
System.out.print(a());
}
And also please, check this out, and start calculate M based on your step 4 from your step by step guide
double Q = 0
into loop Q = <...> * Q what always return 0
Q = Q + M Q and M equal 0 so result still 0

Generate random integers with a range and place them into this array

I am working on a problem for 5 hours, and I searched in a book and on the Internet, but I still cannot solve this problem, so please help me to check what's wrong with the program. And the pic is the requirement for this program.
//imports
import java.util.Scanner;
import java.util.Random;
public class Lab09 // Class Defintion
{
public static void main(String[] arugs)// Begin Main Method
{
// Local variables
final int SIZE = 20; // Size of the array
int integers[] = new int[SIZE]; // Reserve memory locations to store
// integers
int RanNum;
Random generator = new Random();
final char FLAG = 'N';
char prompt;
prompt = 'Y';
Scanner scan = new Scanner(System.in);
// while (prompt != FLAG);
// {
// Get letters from User
for (int index = 0; index < SIZE; index++) // For loop to store letters
{
System.out.print("Please enter the number #" + (index + 1) + ": ");
integers[index] = RanNum(1, 10);
}
// call the printStars method to print out the stars
// printArray(int intergers, SIZE);
} // End Main method
/***** Method 1 Section ******/
public static int RanNum(int index, int SIZE);
{
RanNum = generator.nextInt(10) + 1;
return RanNum;
} // End RanNum
/***** Method 2 Section ******/
public static void printArray(int integers, int SIZE) {
// Print the result
for (int index = SIZE - 1; index >= 0; index--) {
System.out.print(integers[index] + " ");
}
} // End print integers
} // End Lab09
As Tim Biegeleisen and Kayaman said, you should put everything in the question and not just an external image.
You have a lot of errors in your code. Below the code will compile and run but I recommend you to take a look and understand what it has been done.
Errors:
If you are declaring a method, make sure you use { at the end of the declaration. You have:
public static int RanNum(int index, int SIZE);
Should be:
public static int RanNum(int index, int SIZE){
// Code here
}
You also should declare outside your main method so they can be accessed across the program.
If you are passing arrays as arguments, in your method the parameter should be an array type too.
You have:
public static void printArray(int integers, int SIZE) {
// Code her
}
Should be
public static void printArray(int[] integers, int SIZE) {
// Code her
}
Here is the complete code:
package test;
import java.util.Random;
import he java.util.Scanner;
public class Test {
//Local variables
public static final int SIZE = 20; //Size of the array
static int integers[] = new int[SIZE]; //Reserve memory locations to store integers
static int randomNumber;
static Random generator = new Random();
static String prompt;
static final String p = "yes";
static boolean repeat = true;
static Scanner input = new Scanner(System.in);
Test() {
}
/***** Method 1 Section ******/
public static int RanNum (int low, int high) {
randomNumber = generator.nextInt(high-low) + low;
return randomNumber;
} //End RanNum
/***** Method 2 Section ******/
public static void printArray(int[] intArray, int SIZE) {
//Print the result
for (int i = 0; i < SIZE; i++) {
System.out.print (intArray[i] + " ");
}
} //End print integers
public static void main (String [] arugs) {
do {
for (int i = 0; i < SIZE; i++) {
integers[i] = RanNum(1, 10);
}
printArray(integers, SIZE);
System.out.println("Do you want to generate another set of random numbers? Yes/No");
prompt = input.nextLine();
} while(prompt.equals(p));
}
}

I have an error with a math operation Java?

I created a code that is meant to accept a user-input then add 5 to it, this is the code. When I enter any number, It returns 0. EDIT: I moved the reCalculate down under main, nothing changes
package files;
import java.util.*;
public class CalculatorTest {
static Scanner userFirstNumber = new Scanner(System.in);
static int numberReCalculated;
public static int reCalculate(int a){
int numberReCalculated = a + 5;
return numberReCalculated;
}
public static void main(String[] args){
int bobson;
System.out.print("Enter a number, I will do the rest : ");
bobson = userFirstNumber.nextInt();
reCalculate(bobson);
System.out.println(numberReCalculated);
}
}
Your declaration of int numberReCalculated = a + 5; shadows the field declaration static int numberReCalculated;. Either change int numberReCalculated = a + 5; to numberReCalculated = a + 5;, or rewrite the entire code to be idiomatic and organized:
public class CalculatorTest {
static Scanner userFirstNumber = new Scanner(System.in);
public static int reCalculate(int a){
return a + 5;
}
public static void main(String[] args){
int input;
System.out.print("Enter a number, I will do the rest : ");
input = userFirstNumber.nextInt();
int result = reCalculate(bobson);
System.out.println(result);
}
}
I have no idea how "bobson" is a descriptive and self-documenting variable name.

Categories

Resources