Java - "i" cannot be resolved as a variable issue - java

I am working on this program and I keep getting this error in Java Eclipse saying that "i cannot be resolved to a variable." when I try to get the output..
Here is the relevant code.
for (int i = 0; i < animal.length; i++){
animal[i].move();
animal[i].makeSound();
if (animal[i] instanceof Leopard)
animal[i].findTree();
if (animal[i] instanceof Bat)
animal[i].locateInsect();
if (animal[i] instanceof Chameleon)
animal[i].changeColor();
}
System.out.println(animal[i].getName());
System.out.println();
This is the line that shows the error but I am not sure why its causing an error message.
System.out.println(animal[i].getName());

for (int i = 0; i < animal.length; i++){
//...
}
System.out.println(animal[i].getName());
You're trying to reference the i outside of the forloop where you created it, so it doesn't exist.
Simply move System.out.println(animal[i].getName()); inside of the forloop like this:
for (int i = 0; i < animal.length; i++){
//...
System.out.println(animal[i].getName());
}

You need to understands the basics of java variable scope
http://www.java-made-easy.com/variable-scope.html

Related

Java StingIndexoutOfBounds

I keep getting an error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 10
at java.lang.String.charAt(Unknown Source)
at Field.setLocations(Field.java:175)
at Field.(Field.java:39)
at SeaBattle.onePlayer(SeaBattle.java:76)
at SeaBattle.play(SeaBattle.java:36)
at MainClass.main(MainClass.java:7)
public void setLocations() {
Random rand = new Random();
ArrayList<String> locationToSet = new ArrayList<String>();
ArrayList<String> temp = null;
int let, num, incl, incn;
String alpha = "ABCDEFGHIJ";
boolean worked;
for (int i = 0; i < ships.size(); i++) {
worked = false;
start: while (!worked) {
locationToSet.clear();
worked = true;
let = rand.nextInt(9);
num = 1 + rand.nextInt(9);
if (num % 2 == 0) {
//num even or odd
incl = 1;
incn = 0;
} else {
incl = 0;
incn = 1;
}
for (int j = 0; j < ships.get(i).getLength(); j++) {
String loc = "" + alpha.charAt(let) + num;
let += incl;
num += incn;
for (int t = 0; t < ships.size(); t++) {
if (t != i) {
temp = ships.get(t).getLocation();
if (temp.contains(loc)) {
worked = false;
continue start;
}
}
}
locationToSet.add(loc);
}
ships.get(i).setLocation(locationToSet);
}
}
}
the line 175 is
for (int j = 0; j < ships.get(i).getLength(); j++) {
I have no idea why I get this error. If I change the < in == then I don't get the error. But then it won't give my objects their locations.
There are already many resources on this in Stack Overflow which can be found with Googling, but I think the larger issue here is you need to understand how exceptions and errors are telling you something went wrong, and Java can't do what you told it to do because it's not able to.
Looking at the error you posted. That is a stacktrace. You'll see a ton of this in programming, you might hate seeing them but they're your friend, because without them, we can't tell if our program ran properly or not. You can read it from bottom up right after it tells it that an exception of java.lang.StringIndexOutOfBoundsException occurred.
Here's how to read your error from bottom up:
at MainClass.main(MainClass.java:7)
This means that your error started when Java was at this line doing all the function calls. Line 7 of MainClass.java, which jumps to
at SeaBattle.play(SeaBattle.java:36)
That's line 36 in your SeaBattle java. Which goes to
at SeaBattle.onePlayer(SeaBattle.java:76)
to
at Field.(Field.java:39)
to
at Field.setLocations(Field.java:175)
and finally.
at java.lang.String.charAt(Unknown Source)
The last line tells you when you did String.charAt it tried to read from an unknown source, which based on the Exception it gave you, meant that it happened at index 10, possibly meaning your string was only up to 9 characters. (As a guess you probably did a for-loop and tried reading the wrong index)
A good approach is to look at that line and see if you can figure out what's wrong. (Double clicking on the exceptions in IDEs usually brings focus to that point).
If that didn't work..
Use the debugger
If you use Eclipse or Netbeans to write java, they all have a debugger that assists you with well, debugging your code. Set a breakpoint at line 7 of MainClass, or any of those lines in that stack trace and run the debugger to step through your code. Here's a great tutorial on how to do that. Manually stepping through your code will let you see exactly what went wrong, that way you can find your problem. Good luck with your homework assignment, this is a good one to learn about for-loops and reading arrays, go ask your TA if you can't figure out the bug, we're more helpful in person.

Java symbol not found when it should be

here's my code:
for(int i=0; i<plainTextUpper.length()-1; i++)
{
System.out.println(charCodeAt(i));
}
It won't compile though, because it says charCodeAt's symbol was not found. Am I missing a library? The only one I have imported right now is java.util.*
Assuming that this is Java and not Javascript, you probably want this:
for(int i=0; i<plainTextUpper.length()-1; i++)
{
System.out.println(plainTextupper.codePointAt(i));
}
Note that this will not process the last character of plainTextUpper. You probably also want to either get rid of the -1 or change the comparison operator to <= in the for termination test.

Ambiguous java error

public static int intersectionSizeMergeAndSort(studentList L1, studentList L2) {
int intersectionSize = 0;
int[] C = new int[L1.studentID.length+L2.studentID.length];
for(int i = 0; i<L1.studentID.length; i++){
C[i] = L1.studentID[i];
}
for(int i = 0; i<L2.studentID.length; i++){
C[i+L1.studentID.length] = L2.studentID[i];
}
Arrays.sort(C);
int pointer = 0;
while(pointer<((L1.studentID.length)+(L2.studentId.length))){
if(C[pointer] = C[pointer+1]){
intersectionSize = intersectionSize + 1;
pointer = pointer + 2;
}
else {
pointer == pointer + 1;
}
return intersectionSize;
}
}
I have this algorithm I am writing for an assignment. Every time I compile my code, I get an error that I cannot understand in order to debug.
Error is as follows:
Error: /Users/nah/Desktop/studentList.java:137: operator < cannot be applied to int,<nulltype>
the error is pointing to the while loop statement
Not sure if this is directly related to the same error but your line
while(pointer<((L1.studentID.length)+(L2.studentId.length))){
has mis-spelt the second "studentId" and should be "studentID"
while(pointer<((L1.studentID.length)+(L2.studentID.length))){
that is of course unless you happen to have two arrays defined for your studentID class, each with a different case.
I also agree with the other answers related to the "==" comparison operator, but you're telling us the error is related to the while statement
The only error I can see is:
if(C[pointer] = C[pointer+1]){
this should be:
if(C[pointer] == C[pointer+1]){
The following will not work in Java:
if (C[pointer] = C[pointer+1])
This is assignment, its type is int, it cannot be used in the if statement
While loop ? Ok. Debugging is done by simplifying expressions.
The only thing where we see < is the loop condition. Instead of
int pointer = 0;
while(pointer<((L1.studentID.length)+(L2.studentId.length))){
do
int pointer = 0;
int len = ((L1.studentID.length)+(L2.studentId.length));
while(pointer< len){
If error again, simplify the error-raising expression.
I think that this question is mistitled. It is ** ambigous only because you do not attempt to localize it. Post a question only if "<" does not work for two integers. The current question title must be: "how do you debug Java programs?"

NullPointerException on Fragment Array

The declaration of the array.
public ExerciseFragment[] fragments;
The initialization.
fragments = new ExerciseFragment[numberOfWorkouts];
And finally, setting each fragment equal to it's respective ExerciseFragment.
for (int i = 0; i < numberOfWorkouts; i++) {
ft.add(LinearLayoutID, new ExerciseFragment(), "KEY"+i);
fragments[i] = (ExerciseFragment) getFragmentManager().findFragmentByTag("KEY"+i);
}
whyn trying to access fragments[] I always get a NullPointerException and I have searched and searched with no luck, I can't find where I went wrong, hopefully some fresh eyes can!
What about changing it to:
for (int i = 0; i < numberOfWorkouts; i++) {
fragments[i] = new ExerciseFragment();
ft.add(LinearLayoutID, fragments[i], "KEY"+i);
}
Does that still give an error message when you run that?
I'm thinking that getFragmentManager() might be returning null in your question. Since I can't see the code for getFragmentManager, declaration and assignment for ft, and findFragmentByTag, so I can't be sure.

Error in my Java Program '.class' expected

class TwoDimArryAlloc {
public static void main(String[] args) {
int itemno[][] = new int[][] { {2234,2235,2236,2237,2238} , {3334,3335,3336,3337,3338} };
int it;
String itemdesc[][] = new String[][] {{"Womans Item1","Womans Item2","Womans Item3","Womans Item4","Womans Item5"},{"Mans Item1","Mans Item2","Mans Item3","Mans Item4","Mans Item5"}};
for (int i=0; i<2; i++)
{
for(int j=0; j<5; j++)
{
System.out.println(itemno[][]);
}
}
}
}
In the above program, I got the following error:
C:\Java Programs\TwoDimArryAlloc.java:18: '.class' expected
System.out.println(itemno[][]);
^
1 error
Process completed.
Can anyone help me solve this error?
You need to provide the array index:
System.out.println(itemno[i][j]);
^ ^
Instead of
System.out.println(itemno[][]);
you want to say
System.out.println(itemno[i][j]);
Without specifying which indexes you want, it is bad syntax, which confuses the compiler so much that it emits an impenetrable error message.
(The first pass of compilation is to construct a syntax tree, and this happens before the compiler figures out which names denote types and which ones denote variables. So when it sees itemno[][] it reasons that this could be the beginning of a valid expression if only itemno were the name of a type, but in that case the full expression would have to be itemno[][].class -- so that's what it asks for even though you meant something entirely different).
{
int itemno[][] = { {2234,2235,2236,2237,2238} , {3334,3335,3336,3337,3338} };
int it;
String itemdesc[][] = {{"Womans Item1","Womans Item2","Womans Item3","Womans Item4","Womans Item5"},{"Mans Item1","Mans Item2","Mans Item3","Mans Item4","Mans Item5"}};
for (int i=0; i<2; i++)
{
for(int j=0; j<5; j++)
{
System.out.println(""+itemno[i][j]);
}
}
}
You forgot to provide index in SYSO statement. Make it as follow:
System.out.println(itemno[i][j]);
You forgot to use the indexes:
System.out.println(itemno[i][j]);

Categories

Resources