"cannot find symbol" error in netbeans ( Java Netbeans 6.5 ) - java

For my final project in introduction to Java, I decided to do a Mastermind Peg Game.
This is the submit button code:
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
Integer guess1, guess2, guess3, guess4;
Integer rightnumber = 0, rightposition = 0;
guess1 = Integer.parseInt (firstInput.getText());
guess2 = Integer.parseInt (secondInput.getText());
guess3 = Integer.parseInt (thirdInput.getText());
guess4 = Integer.parseInt (fourthInput.getText());
//Values are compared to the actual guess.
//(THIS IS WHERE I GET THE FOLLOWING ERROR:
//"cannot find symbol, symbol : variable answerdigit,
//location: class finalproject.Singleplayer"
if ( guess1 == answerdigit[0]);
{
rightposition = rightposition + 1;
}
}
This is the Start button. Here, the 4 digit answer/code is produced.
private void startButtonActionPerformed(java.awt.event.ActionEvent evt)
{
// Declare variables for 4 digit answer, guess for each number
Integer one, two, three, four;
//Generate random number between 1 and 6 for each digit in the answer
int[] answerdigit = new int[4];
for(int i=0;i<4;i++)
{
answerdigit[i]=(int)(Math.random()*6+1);
}
}
I get an error:
cannot find symbol, symbol : variable answerdigit, location: class finalproject.Singleplayer
I don't understand what the error means.

answerdigit is not accessible because you have declared it somewhere & it is only accessible to that local scope, for accessising it else anywhere you have to declare it in class
e.g.
class cls
{
int[] answerdigit;
//your remaining code
}
you have declared it in
private void startButtonActionPerformed(java.awt.event.ActionEvent evt)
and accessing it in
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt)
thats why it is giving error.

You have a variable scope problem it seems: answerdigit is declared local to the startButtonActionPerformed method and thus only visible inside of this method and simply doesn't exist elsewhere. If you want to use this variable elsewhere in the class, then the array variable, answerdigit, must be declared in the class.

int[] answerdigit = new int[4]; should be in the scope of the class not in the scope of private void startButtonActionPerformed(java.awt.event.ActionEvent evt) this method!
Just put int[] answerdigit = new int[4]; this statement out of the method and your code will be fine... :)

Related

(JFrame) How do I read a random number to compare in a different method without displaying it?

I'm trying to make a number guessing game. When the user presses the start button, the program will randomly generate a number. The user can then input a number and the program will tell the user if they need to go higher or lower, after 8 guesses the program stops.
I have managed to generate a random number and write a loop that allows the user to guess 8 times. There are no compiling errors but I get a lot of errors when pressing the "guessBtn". This is my code:
private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Random rand = new Random();
int getal = rand.nextInt(100)+1;
}
private void guessBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String randomNumTxt = startBtn.getText();
int getal = Integer.parseInt(randomNumTxt);
String gokNumTxt = guessTxt.getText();
int gok = Integer.parseInt(gokNumTxt);
int aantalGok = 0;
while ((gok != getal) && (aantalGok <9)){
if (gok < getal){
antwoordLbl.setText("Hoger!");
aantalGok++;
}
if (gok > getal){
antwoordLbl.setText("Lager!");
aantalGok++;
}
}
if (gok == getal){
antwoordLbl.setText("Geraden!");
}
else if (aantalGok == 8){
antwoordLbl.setText("Jammer, het getal was "+getal);
}
}
I figured that I'm doing something wrong when trying to read the randomly generated number but I can't figure out how to do it correct. Any tips?
From the comments and based on your code, consider the below class where actual stores a randomly generated value each time the "start" button is clicked. As an instance variable (not class variable as mentioned in the comment), the value continues to be available between methods of the same instance of the class.
public class MyFrame extends JFrame implements ... {
// keep track of a randomly generated value
private int actual; // part of the class, not within a method
// each instance of the class will have its own value
// the variable exists as long as the instance exists
private void startBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Random rand = new Random(); // this could also be an instance variable instead of creating a new one each time
// int getal = rand.nextInt(100)+1; getal would be a local method variable and is lost when the method returns
actual = rand.nextInt(100)+1; // keep track of the random value
}
private void guessBtnActionPerformed(java.awt.event.ActionEvent evt) {
...
int guess = ... // whatever the user guessed
if (guess == actual) {
...
} else if (guess > actual) {
...
} else {
...
}
}
}
Further reading: search on "java variable scope".

New method, <identifier> expected error

I'm trying to write a program (for an assignment) that will – based on two absolute parameters – determine wether or not someone will be eligible for financial support. To accomplish this I have created three new methods, and currently I'm down to 1 error that I simply cannot comprehend. The error says "identifier expected" on this part of the code (in the bottom:
static void metodeTekst(tekst)
Here is my code:
import java.util.Scanner;
public class MinOppgave2a
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
String tastatur;
System.out.println();
System.out.println("\r\n" + "For aa kunne beregne ditt stoettegrunnlag, må du oppgi alderen din: ");
tastatur = in.nextLine();
int alder = Integer.parseInt(tastatur);
System.out.println();
System.out.println("\r\n" + "Bor du hjemme? Skriv 1 for «Ja», eller 2 for «Nei»: ");
tastatur = in.nextLine();
int hjemme = Integer.parseInt(tastatur);
System.out.println();
int i = 0;
while (i < 2)
{
i = i + 0;
}
metodeAlder(alder);
metodeHjemme(hjemme);
System.out.println("Du vil faa full studiestoette!");
}
static void metodeAlder(int alder)
{
if (alder <= 18 || alder >= 45)
i++;
else
metodeTekst(tekst);
}
static void metodeHjemme(int hjemme)
{
if (hjemme == 2)
i++;
else
metodeTekst(tekst);
}
static void metodeTekst(tekst)
{
String tekst = ("Du vil faa redusert eller ingen studiestoette.");
System.out.println(tekst);
}
}
I've tried for a good while to find an answer online, but in most cases where people have gotten this error they have forgotten to write a main method. I have not, as you see. Thanks in advance – I'm really new to Java, and appreciate all help!
Your method metodeTekst is wrong. It should either be
static void metodeTekst()
{
String tekst = "Du vil faa redusert eller ingen studiestoette.";
System.out.println(tekst);
}
or
static void metodeTekst(String tekst)
{
System.out.println(tekst);
}
but then you have to call it like this:
metodeTekst("Du vil faa redusert eller ingen studiestoette.");
Edit for OP's comment:
There are many additional problems with your code. The variable i in metodeAlder and metodeHjemme is outside if the scope of where i is initially defined (in main). If you really need to alter this variable inside your methods you have to declare it as a static field outside of your main.
Besides after everything compiles fine, this part
while (i < 2)
{
i = i + 0;
}
is pointless. You'll end up in an endless loop since you never change i so it will always be < 2. I would remove all occurrences of i since it doesn't do any meaningful and is not at all needed in your program.
Edit 2:
For your question as to why the compiler only now complains about i: It first checked, if all your method signatures were correct. Since it ran into previous error (with the wrong signature), it didn't need to check further. Now that you've fixed it, the compiler could continue to check the syntax "inside" the methods. And since i is only defined outisde of the method's scopes, it didn't know what i is supposed to be, hence the next compiler error.
Edit 3:
To make my explanation clearer look at the following example:
{
// Outer Scope
{
// Inner Scope A
}
{
// Inner Scope B
}
{
// Inner Scope C
}
}
Here, the three inner scopes A, B, C are isolated from each other. So variables defined in inner scope A are not visible to the other inner scopes B and C. In contrast, variables defined in the outer scope are visible to all inner scopes, since they are part of the outer scope as well.

Why can't these variables be resolved?

I need to write a program and, in one step of it, I need to construct a function that calculates the number of rabbits.
The problem is that Eclipse shows a message saying that the variable I created "cannot be resolved to a variable" and I don't understand why it happens. Can someone help me?
Here is part of my code
I am showing all my code because it would get bigger and it is not needed, in order to solve this problem
class Rabbits {
static int nbRabbits = initRabbits; // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
static int nbFoxes = initFoxes; // ERROR HERE!!!!!!!!!!!!!!!!!!!!!!!!!!
int rabbits = 0;
public static int calculateRabbits(int rabbits, int foxes, double AttackRate) {
for (int i = 0; i < Duration; ++i) {
rabbits = nbRabbits;
nbRabbits *= (1.0 + Rabbits_growth_rate - AttackRate * nbFoxes);
}
return nbRabbits;
}
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
// Enter initial population
int initFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
int initRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits
// SOME MORE CODE HERE
} // end main
} // end of class
initRabbits and initFoxes are variables entered by the user when I call enterPopulation method.
I'm new to Java and, unfortunately, I cannot change the logic of this code. For example, I cannot put the calculateRabbits method inside the main neither change the begin or the end of the code.
initRabbits only exists within the main method. That is it's scope.
You are attempting to statically reference something it can't see. You are attempting to populate nRabbits before a value for innitRabbits exists. This is impossible.
Your trying to assign a value to your nb variables from a variable that hasn't been created yet. Skip making four variables and just assign the nbs to 0 outside of your main class, then give them the value you want inside it. They will then retain that value outside of the main class and be visible.
static int nbRabbits = 0;
static int nbFoxes = 0;
//in main class
nbFoxes = enterPopulation("foxes", 2, keyb); //at least 2 foxes
nbRabbits = enterPopulation("rabbits", 5, keyb); //at least 5 rabbits

How to output binary search answer?

I get the error message cannot find symbol, symbol: method books(int[], int) when I try to compile the following code.
For further explanation about what I want the code to do, see below the code.
public class books {
public void main(String[] args) {
int searchValue = 0, index;
int refNum[] = new int[4]; // the array
refNum[0] = 4; //numbers to refer to (aka to find)
refNum[1] = 6;
refNum[2] = 10;
refNum[3] = 12;
refNum[4] = 14;
int input = Integer.parseInt(enterValue.getText()); //takes user's input
for (int x = 0; x < refNum.length; x++) {
refNum[x] = input; //Tells refNum value to be
}
searchValue = input;
index = books(refNum, searchValue); //"books" is underlined
if (index != -1) {
binarySearchField.setText("We found: " + index);
} else {
binarySearchField.setText("Sorry! Not Found!");
}
public static Boolean binarySearch(String [] refNum, int left, int right, String search){
//Boolean code for later
}
This program uses binary search to find values stored in array after user inputs number, if they match then the item is successfully found. User inputs desired number in 'enterNumber' which is a TextField. Now in my code )which I'm 78% sure will work if it wasn't for this one little thing) there is an all important that is underlined which shouldn't be, (I've commented beside the line to show)
Now I had thought I was suppose to put the class name there, but apparently since it is underlined that is not the case. Any ideas on what I should be putting there in it's place?
And I apologize for the question may be a bit misleading on what I'm really asking, I just wasn't sure how to word the question.
The line
index = books(refNum, searchValue);
seems to be underlined because you have no method called books that takes an int[] and an int as arguments in your books class definition.
Now I had thought I was suppose to put the class name there Why do you assume you have to put the class name there? Figure out what you are trying to do with this code and then you will understand what goes in that line (at least in pseudocode).
Also it seems like you have a method declared directly inside another method. That is not legal in java. If this is not the case, please show us correct code.
books is your class's name..that might be the reason you are getting this error. You can't call constructor like a method. Change class's name to Books or something else..or change method's name

Changing a variable though a module in a loop (java)

So I am trying to write a simple program for my Java class and I have asked the teacher for help however, this is a distance learning class and am not getting much help from that direction. So here I am.
The problem we have been asked to solve is to create a program that will
(1) ask the user for a number ,
(2) find the sum of all user defined numbers ,
(3) find the average of these numbers ,
(4) then out put them back to the user.
I use the numbers not only to line through things I have finished but because they must be separate modules to be called.
How can i get the userNum variable to update durring the while statments. Currently they are not. OR is there a simpler way to do this that im overlooking. Any help is greatly appreciated. Thank you.
public class P2 {
public static void main(String[] args) {
int userNumCount = 1;
double userNum = input();
double userSum = sum(userNum);
double userAverage = average(userSum, userNumCount);
sum(userNum);
while (userNum != 0 && sum(userNum) <= 100){
++userNumCount;
output(userSum, userAverage);
input();
sum(userNum);
average(userSum, userNumCount);
}//end else
while (userNum != 0 && sum(userNum) >=100){
++userNumCount;
JOptionPane.showMessageDialog (null, "Warning, your sum is currently over 100!!!!!");
output(sum(userNum), userAverage);
input();
sum(userNum);
average(userSum, userNumCount);
}//end else
if (input() == 0){
output(userSum, userAverage);
JOptionPane.showMessageDialog (null, "Thank you for using this program have a nice day.");
}//end else if
}//end main module
public static double input(){
String userNumString;
userNumString = JOptionPane.showInputDialog("Please enter your number or input 0 to end the program.");
double userInput = Double.parseDouble (userNumString);
return userInput;
}//end input module
public static double sum(double userNum){
double userSum =+userNum;
return userSum;
}//end sum module
public static double average (double userSum, int userNumCount){
double userAverage = userSum/userNumCount;
return userAverage;
}//end average module
public static void output (double userSum, double userAverage){
JOptionPane.showMessageDialog (null, "The sum of the numbers input so far is: " + userSum + ". And the Average is " + userAverage + "." );
}//end output module
}//end class
All of the values returned from methods in your main are just returning their values to nothing. When you pass variables to a function, they are passed by value. For example:
public void main(String args[]){
int f = 5;
doSomething(f);
System.out.println(f);
}
public int doSomething(int i){
i+=1;
return i;
}
The value returned by doSomething is 6, but the program outputs 5. When you call a function the int i is recreated independently of f. As of now, your program is just throwing those values away and keeping the old ones.
Also you have the variables in main called userSum, and userAverage, and in sum and average you redefine these in a different scope. When code flow comes into sum and average it creates new variables for that method. If you want these values to be the same you need to make them static, by defining them outside of your main method and declaring them static.
I think the problem you might be struggling with is scope. Pretty much every time you have an opening bracket the program changes scope. When a block is closed (when there is a closing bracket}, the scope of the variables ends, ie. they don't exist anymore. For example:
class someClass
{
//Block 0
static int staticNum = 0;
public static main(String args[])
{
//Block 1
int level1 = 0;
if(true)
{
//Block 2
int level2 = 0;
} else {
//Block 3
level1++; //ok because the level1 is accessible from here
staticNum++; //ok because staticNum is static
}
//resume block 1
level2++; //not ok because level2 was in a different scope
doSomething(level1)
}
public static void doSomething(int i){
//Block 5
int level1 = 0; //different than the one in the main method
i++; //ok but once execution leaves i wont exist anymore
staticNum++; //ok because staticNum is static and exists in the class's scope
level1++; //not ok because level1 is not defined for this scope
}
}
While execution is in a block, it can access any variable in blocks 'above' it in nesting level. Looking at the above, in Block 2 and 3 you can access anything in block 1 or block 0. Block 3 doesn't have access to the variables in block 2 because they are out of scope of one another, because when a block closes all variables instantiated in that block are freed. Block 5 has a completely different scope than block 1,2 and 3.
Block 0 is special because it is associated with the class. Anything outside of method bodies declared static are class wide variables, as in you can access it where ever you have access to the class. You would use something like ClassName.staticNum to access it in another class. Also when you access it inside of the class, any methods that you use the static values in need to be declared static as well.
Anything not declared static in the class body is an instance variable. It is associated with an instances of the class, these instances called objects. A class defines the template of an object. For example, lets say we have two objects of type Computer. The class Computer defines what variables each individual computer has(instance variables), and what variables every computer shares(static variables). So if I have Computer A with instance variables mouse and keyboard, it is completely different from another Computer B instance variables mouse and keyboard, but they can share a static variable called Computer.innernette.
This is incorrect.
public static double sum(double userNum){
double userSum =+userNum;
return userSum;
}
In a basic pseudo-language this is happening each time this method is called
receive userNum
create userSum
set userSum = 0
add userNum to userSum
give userSum
each time the method will return the value it is given, not the running total I think you are expecting.
If you have two variables declared with the same name, they are still different. What you want to do is refer to the same variable, to do this you need to have the references in the scope where the variable is declared.
to get the running total
public class P2 {
public static double userSum = 0;
//because this is a public member it's scope is global i.e. you can refer to it anywhere.
...
public static void main(String[] args) {
...
/* do not declare userSum here.
if you do any reference to userSum will use the local variable
not the global variable.
double userSum = 0; <-- declare local variable it's scope is until the
end of this method nothing outside the method
can see it but you can pass it as a parameter
userSum = 1; <-- local variable is set to 1
P2.userSum = 2; <-- local variable is set to 1 global is set to 2
*/
input();// for this the input method is called and returns a value,
// but you haven't said to put it anywhere so java will throw it away
// all that effort for nothing.
userNum = input(); // in this case it will put the new value in userNum.
}
public static double sum(double userNum){
userSum =+userNum; // do not declare userSum use it from the class context
return userSum;
}
...
}
for further reference scope

Categories

Resources