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
Related
Is this code safe in Java?
public class HelloWorld {
public static void main (String args[]) {
HelloWorld h = new HelloWorld();
int y = h.getNumber(5);
int z = h.getNumber (6);
if (y == 10)
System.out.println("true");
}
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
}
My co-worker says that int number will be placed on the stack and when getNumber returns it will be popped off and could potentially be overwritten.
Is the same code potentially unsafe in C?
The HelloWorld class has no fields, and is therefore immutable. You can call your getNumber(x) function as many times as you'd like, from any thread, using the same object, and it will always give the same result for the same argument.
Maybe your co-worker is recalling horror stories in C where you can have something like static int number, which "belongs" to the method and which would get overwritten. Or maybe she's thinking about "return by reference"; even if it were, you'd be referencing a brand-new object every time because number is newly instantiated for every method call.
Your coworker is correct, sort of, but they apparently misunderstand what is going on.
public int getNumber(int x) {
int number = 5;
number = number + x;
return number;
}
Yes the value of 5 + 5 or 5 + 6 will be placed on the stack, but there is no danger of them being overwritten, they will properly be placed into y or z.
I suspect the confusion is from C (this type code works fine in C as well), but for pointers instead of primitives. Returning a result of malloc from a function in C can be "challenging" if you don't do it right.
I'm creating Java Program which one prints out as many For loops as user wants to. I'm creating variables in for wih the random -generated string. The user can choose how long the variable will be. My problem is, when I try list my variables for testing this code work, I can't see anything printed out on the screen when I'm using listVariables() -method. If I try to put System.out.println inside the generateVariables(), The new generated strings are in the ArrayList -vector. The code is clear, and it will run on console, but nothing seems to be printed out. Where's the catch?
Here is my code
import java.util.Random;
import java.util.ArrayList;
import java.lang.StringBuffer;
public class Silmukkageneraattori {
//Attributes
//Change the value for how many loops you want to create?
private static final int howManyLoops = 5;
//Next string -array includes all the generated variables;
private static ArrayList<String> variables = new ArrayList<String>();
//Next value is how long variable name do you want to create?
private static final int howLongVariable = 2;
//Next method generates variables
public static void generateVariables(int how) {
String temp = null;
for (int x=0;x<how;x++) {
variables.add((String)createVariable());
}
}
//Next method creates variable
public static String createVariable() {
Random rand = new Random();
StringBuffer sb = new StringBuffer("");
String chars = "qwertyuiopasdfghjklzxcvbnm";
for (int x=0;x<howLongVariable;x++) {
sb.append(""+chars.charAt(rand.nextInt(chars.length()-1)));
}
return sb.toString();
}
//Method for listing created variables;
public static void listVariables(ArrayList<String> varB) {
for (int x=0;x>varB.size()-1;x++) {
String var = (String)varB.get(x).toString();
System.out.println(var);
}
}
//Main -method
public static void main(String[] args) {
generateVariables(howManyLoops);
listVariables(variables);
}
}
In the below for loop in this method:
public static void listVariables(ArrayList<String> varB) {
for (int x=0;x>varB.size()-1;x++) {
String var = (String)varB.get(x).toString();
System.out.println(var);
}
}
You are running the loop until x becomes smaller than varB.size()-1 (or until varB.size()-1 is greater than x).
However, varB.size()-1 does not change size within your loop. Thereofre, it will always be be greater than x and x will always stay smaller than varB.size()-1. Consequently, the loop never runs.
It appears you only want to get one element from varB, the first one, so why not remove the for loop altogether and just do:
System.out.println(varB.get(0));
Change
for (int x=0;x>varB.size()-1;x++) {
to
for (int x=0;x<varB.size()-1;x++) {
Note the change of > to < in condition in above for.
you have used > condition so 0 never will be greater then 4. so the condition required like it start from 0 to 4. till x will be lesser then total varB.size().
for (int x=0;x<varB.size()-1;x++)
instead of
for (int x=0;x>varB.size()-1;x++)
Your problem is in the listVariables method.
You are using a > (greater than) rather than < (smaller than).
Once listVariables is called, x is 0, and varB.size is some value (5). At the test condition, the loop will not be entered since 0 is not greater than 5.
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
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... :)
I'm trying to get back into Java - it's been about 5 years since I studied the basics and I've been lost in the .Net world since.
I'm trying to create a student class below, however the for loop for reading in the integers into the array gets stuck when the program runs.
From my previous knowledge, and from research, the loop seems to be constructed properly and I can't seem to figure out where it's going wrong.
I'm sure it's something silly - as always but I was wondering if someone could point me in the right direction? :)
import java.util.*;
import acm.io.*;
public class Student {
// instance variables
private int studNumber; //Must be between (and including) 0 and 99999999. If input value invalid default to 0.
private String studName;
private int marks[];
/*
* Constructor Student Class
*/
public Student(int studNumber, String StudName, int marks[]) {
// initialise instance variables
if (studNumber >=0 && studNumber<= 99999999) {
this.studNumber= studNumber;
} else {
this.studNumber = 0; //default value
}
this.studName= StudName; // no validation
this.marks = marks;
IOConsole console = new IOConsole();
for (int i = 0; i <= 6; i++) {
marks[i] = console.readInt();
}
}
}
I think that the problem lies here:
for (int i = 0; i <= 6; i++)
{
marks[i] = console.readInt();
}
The only instance where I found a reference to IOConsole was here and it does not seem to be something which is part of the standard Java framework.
If you just need to scan numbers from console, you can use the Scanner class and the use the nextInt() method like below:
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 6; i++)
{
marks[i] = input.nextInt();
}
The loop seems correct. Is it possible the console.readInt() call is blocking, which keeps you stuck in the loop (the IOConsole class is not part of the standard JDK, and I am not familiar with it)
readInt() is waiting for user input
from http://jtf.acm.org/javadoc/student/acm/io/IOConsole.html#readInt%28%29:
Reads and returns an integer value from the user
The problem is with console.readInt(), where another non-stop loop is executing or some other problem with that method
I believe the problem lies in the readInt() part. It's unusual to read input from the Console in a constructor for initializing the attributes, delegate that task to another part of your code and move it outside the constructor.