I am building a RPG character generator and am having a semi-difficult time with the stats of the character. The reason I am having issues is this:
int base = 10;
int iStrengthStatPoints = scan.nextInt();
int iStrength = (base +iStrengthStatPoints);
It won't compile because I am outputting the variable "iStrength" later in my code and it says cannot find symbol. I realize it is due to having iStrength being set to the value of base + iStrengthStatPoints. So I am wondering if there is a way I can assign a starting value to iStrengthStatPoints and then have the option to input a new value later on.
The thought I had was something like this:
int iStrengthStatPoints = 0;
int iStrengthStatPoints = scan.nextInt();
It would have the base value 0 but later on I could input an overriding value. Is this possible? If not is there a way to do something similar?
If you compiler is saying that it cannot find the symbol, you are trying to print iStrength out of its scope. Chances are you are declaring the variable in one method, giving it scope local to the method, and then trying to print it later in another method. This would be true even of variables declared in the class's constructor.
You only need to declare the variable (using the int keyword or other type-name) once; after that, you can assign to it (change its value) many times. So, this is fine:
int iStrengthStatPoints = 0;
and you just need to change this:
int iStrengthStatPoints = scan.nextInt();
to this:
iStrengthStatPoints = scan.nextInt();
The problem is not with the assignment statement that updates iStrength. Rather, it is with the scoping of the declaration iStrength. More precisely, the iStrength identifier is out of scope at the point you are trying to print it.
Unfortunately, neither the declaration or the problematic print code are in your code snippet, so it is not possible to say exactly what the problem is and how to fix it. Even guessing what the problem might be is futile, because there are (in general ... i.e. without seeing your code) too many possibilities.
If you want a better diagnosis, include (at least) everything from the declaration to the code that is giving the compilation error.
Related
I am new to learning Java and was explained that every variable needs to be declared. Why do I not need to do this in two steps?
int a = Integer.parseInt(console.readLine("How old are you? "));
console.printf("a: %d", a);
You don't need to declare a variable, but when you do so, you must specify a type (or a super type of what is on the right hand side).
The return value of console.readLine("How old are you? ") is a String and printf can take that as a parameter, so there is no missing type information.
Nothing stops you from writing it in one line, i.e.
console.printf("a: %d", Integer.parseInt(console.readLine("How old are you? ")));
This will work without any problem. Writing it in one line becomes a question of preference / readability and whether you want to do anything with the variable before you print it...
As to your comment, you can check in documentation that console.readLine() returns String.
I know there are similar questions about simple variables in C, but I guess this one is a bit different...
I have an int value named occurrences where I want to assign to it a value from a function like that:
occurrences = GPOINTER_TO_INT(g_hash_table_lookup(Sip_income2, headersDigest[i]));
My problem is that when i try to assign to this variable a value by using the hashtable_lookup function ,as I already showed above, then this value in java is equal to 0.
However, if I assign a value in a variable occurrence e.g
occurrences = 5;
and then i pass this variable as a parameter to a java function with JNI this value is indeed equal to 5 in java, so there is no problem with that.
What should the problem that causes all that and is there any possible solution?
I have two programs. I create a static array and some methods such as the following:
public Someclass{
static int counter[] = new int[n];
//methods & main
}
the n is defined to be some number, so I know it will have some length. I later fill this array and I test to see that it gets filled correctly, so I know some indexes should have values other than 0. Now when I try to call it in second program, it is though I never filled it because it only gives me 0's.
//second program
public Someclass2{
public static main(String[] args){
String n = "someword"
int[] nums = new int[n.length]
for( int i = 0; i < n.length; i++){
nums[i] = nums[i] + (25 * SomeClass.counter[i]);
}
}
}
For some reason, when I call the array in the second program it returns all zeros and doesnt change the value of nums, even though I know the counter array should have non-zero values. I think it has to do with the fact that I initialize it statically but I filled it in a local method and in the class. So techincally it never gets it's zeroes updated. I am having trouble trying to fix this and if anyone could help I would aprreciate it.
Thank you
My guess: you're filling the array inside of SomeClass, but never call that filling code before using the array in the other class. Solution: be sure to fill it first. For more specific help, show us more details about your code.
Other points -- it is usually best to avoid use of static fields, and instead it is usually better to make the array an instance field. Then you can ascertain its state through its containing class, and also change its state through the containing class with any restrictions that you'd like to put on the ability to change it.
If the second 'program' is really a separate program and not just another class, then it won't work the way you want it to. When the second program calls the static class, it will just create a new array for the second program, while the original array you filled in the first program persists for the first program. Static variables are only accessible to other parts of the same program, not all programs running on the computer.
The problem is here: nums[i] = nums[i] + (25 * SomeClass.counter[i]);
Basically you have created an array and haven't populated it. So if n = 5 then counter == {0,0,0,0,0} . This means that each index gets the default value of 0 so everytime you do this : 25 * SomeClass.counter[i] you multiply with 0 which of course returns 0
There is nothing that happens in Someclass2.main() that would cause the static array in Someclass to be filled. It is all zeroes because that is how the Java spec defines it:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type int, the default value is zero, that is, 0.
The second program never does anything to modify the state of Someclass.counter resulting in getting all zeroes.
I have some code, like so:
int batchPosition = new Integer(batchBegin);
for (batchPosition;batchPosition<=batchEnd;batchPosition++)
But I get this error in eclipse:
Syntax error, insert "AssignmentOperator Expression" to complete ForInit.
I've looked at various posts on SO about this error, and googled it but I can't figure out why this isn't allowed.
batchPosition on it's own is not a valid initialisation statement - you can simply skip it:
int batchPosition = new Integer(batchBegin);
for (; batchPosition <= batchEnd; batchPosition++)
But if you don't need to access batchPosition after your loop, it is good practice to reduce variables scopes as much as possible:
for (int batchPosition = new Integer(batchBegin); batchPosition <= batchEnd; batchPosition++)
For some reason Java or Eclipse (or bother) doesn't like this part of the loop:
for (batchPostion....
It expects the variable being used to count position (batchPosition) in the loop to be initialised in the loop header (the for(first;only when;repeat) part.) I would guess this is because wants it to only be local to the loop.
To fix just move you assignment into the header, like so:
for (int batchPosition = new Integer (batchBegin);batchPosition<=batchEnd;batchPosition++)
Not as pretty, but it will work.
for loop contains 4 parts of execution:
initialization, Condition, execution-body, increment or decrement
int batchPosition = new Integer(batchBegin);
for (batchPostion;batchPosition<=batchEnd;batchPosition++)
You've missed the initialization part.
Either ignore it at all cause before for you've already initialized
for (;batchPosition<=batchEnd;batchPosition++)
OR
Move the line before for to inside for
for (int batchPosition = new Integer(batchBegin);batchPosition<=batchEnd;batchPosition++)
but, in latter case, you won't be able to use batchPosition outside for scope.
The string called "code" doesn't seem to read. Why is that and how do I fix it?
My code (the snippet that causes problems):
String code;
for(int z = 0; z<x;z= z+0) // Repeat once for every character in the input string remaining
{
for(int y=0;y<2;y++) //Repeat twice
{
c = (char)(r.nextInt(26) + 'a'); //Generate a random character (lowercase)
ca = Character.toString(c);
temp = code;
code = temp + ca; //Add a random character to the encoded string
}
My error report:
--------------------Configuration: <Default>--------------------
H:\Java\Compiler.java:66: variable code might not have been initialized
temp = code;
^
1 error
Process completed.
(I am using JCreator 5.00, Java 7.)
(Yes, the error report looks stupid, but it Stack Overflow reads it as coding.)
What value would code have if x is zero? The answer is it would have no value at all (not even null). You could just initialize it to an empty string if you like:
String code = "";
Java requires that every variable is initialized before its value is used. In this example, there is a fairly obvious case in which the variable is used before it is assigned. The Java Language Spec (JLS) doesn't allow this. (If it did, the behaviour of programs would be unpredictable, including ... potentially ... JVM crashes.)
In other cases, the compiler complains when in fact the variable in question is always initialized (or so it seems). Rather than "understanding" your code, or trying to derive a logical proof of initialization, the compiler follows a specified procedure for deciding if the variable is definitely assigned. This procedure is conservative in nature, and the answer it gives is either "it is initialized" or "it might not be initialized". Hence the wording of the compilation error message.
Here is an example in which the compiler will complain, even though it is "obvious" that the variable is initialized before use:
boolean panic;
for (int i = 0; i < 10; i += 2) {
if (i % 2 == 1 && panic) { // compilation error here
System.out.println("Panic!!");
}
}
The definite assignment rules (specified in the JLS) say that panic is NOT definitely initialized at the point indicated. It is a simple matter for a person who understands the basics of formal methods to prove that i % 2 == 1 will always be false. However, the compiler can't. (And even if it could, the code is still in error given JLS rules.)
You've created a reference, but you've never initialized it. Initialize code by changing the first line to
String code = ""
Edit: Zavior pointed out that you can pull an initialized string from the cache rather than allocate space for a new one.
But why are you assigning temp to code and then code to temp plus something else? It can be set to code = code + ca.