Array variable "might not have been initialized" - java

I get the error:
TestCounter.java:115: variable
counters might not have been
initialized
counters[i] = new Counter(i);
And I can't figure out how to fix it. I know that my class, Counter, works. Below is my code, if you could have a look at it I would be very happy. This code is wrapped in the main method of a TestCounter class.
if(success)
{
Counter[] counters;
for(int i=0; i<30; i++)
{
counters[i] = new Counter(i);
System.out.println(counters[i].whatIsCounter());
}
}

You haven't created the array, you've just declared the variable.
You need to do this:
Counter[] counters = new Counter[30];
or something similar

You need to initialize the counters array.
Something like this:
if(success)
{
Counter[] counters=new Counters[30];
for(int i=0; i<30; i++)
{
counters[i] = new Counter(i);
System.out.println(counters[i].whatIsCounter());
}
}
By stating Counter[] counters you are not actually creating an array, you are simple declaring a reference variable counters of type Counter[].
Counter[] counters=new Counters[30] will create an array of type Counter of size 30 with each element holding null reference.

Related

Variable is assigned but never accessed

I'm new to Java and trying to do a simple count operation in a for loop:
public boolean play(Matrix matrix){
int dimension = matrix.getDimension();
int count=0;
for(int x=0;x<dimension;x++){
for(int y=0;y<dimension;y++){
count++;
}
}
return true;
}
The error I get is related to count and is as in the title: Variable is assigned but never accessed.
The variable count should have been initialized outside the for loop and then accessed inside the for loop, I don't understand where the problem is located.
Like GriffeyDog wrote: You never use (read from) the variable count, you just assign to it. That was the problem.

int cannot be converted to int []

new to programming here and i keep getting the error message, incompatible types, int cannot be converted to int [], the question is to add R1 & R2 together if they are of equal lengths and if not, print a message that says 'the arrays must be same length', if that matters, not sure where im going wrong, any help would be greatly appreciated
public int[] arrayAdd(int[] R1, int[] R2)
{
int[] sumArray= new int[R1.length];
if( R1.length!= R2.length)
{
System.out.println("The arrays must be same length");
}
else
{
for(int i=0; i< R1.length; i++)
for (int j=0; j<R2.length; j++)
{
sumArray= R1[i]+ R2[j]; // Error
}
}
return sumArray;
}
not sure where im going wrong
You are attempting to assign an int to a variable whose type is int[].
That is not legal ... and it doesn't make sense.
This:
sumArray= R1[i]+ R2[j];
should be this
sumArray[something_or_other] = R1[i] + R2[j];
... except that you have a bunch of other errors which mean that a simple "point fix" won't be correct.
Hint: you do not need nested loops to add the elements of two arrays.
sumArray[i]= R1[i]+ R2[j]; // updated line
you need to assign to an array element, but you were doing it wrong.
Your code is broken in many several ways, at least:
You declared returning an array but what is the value of it when inputs are of the wrong size? Manage such errors in better ways (stop, throw exception, return error code, etc). At least never display something at this place, this is not the place were you have to tackle the error, this is the place here you detect it, just report it to caller(s).
You (tried to) created space for the returned value but how could this be if conditions for having a return value is not met?
You used Java syntax to declare an array, int []sumArray should be `int sumArray[0].
You can't dynamically allocate an array like this, to capture a dynamic allocation you must use a pointer, an array is not a pointer. But a pointer can be set to the memory address of an allocated array, like int *sumArray = new int[10]
sumArray is an array so to set an element of it use sumArray[index] = ...
So this may be better:
public int *arrayAdd(int[] R1, int[] R2) {
if( R1.length!= R2.length) {
return nullptr;
}
int *sumArray= new int[R1.length];
for(int i=0; i< R1.length; i++) {
sumArray[i] = R1[i]+ R2[i];
}
return sumArray;
}
After question editing
If you want to sum two arrays, element by element, then a single loop is sufficient...
Actually in that line sumArray is an integer array and you are assigning it as integer only and also you haven't declared variable j.
Try this-
public int[] arrayAdd(int[] R1, int[] R2)
{
int[] sumArray= new int[R1.length];
if( R1.length!= R2.length)
{
System.out.println("The arrays must be same length");
}
else
{
for(int i=0; i< R1.length; i++)
{
sumArray[i]= R1[i]+ R2[i]; // Error
}
}
return sumArray;
}

Array result keep getting the last result

I put a partial of my code which I think is the source of problem but I could not figure out hence why I am at StackOverFlow now. Anyways this Class is where i set my data and pass it into an array.
public ArrayList<select.rates> caseGetRates() throws RateTableException, SessionDisconnectedException {
try {
for(int i=0;i < arrayRate.size();i++){
ArrayList<select.rates> arr = new ArrayList<select.rates>();
this.setPair(array[0]);
this.setBid((array[2]));
this.setAsk((array[3]));
arr.add(this);
}
return arr;
} finally{}
}
When I System.out.print the data which I set in this class it gives me:
EUR/USD
1.12372
1.12384
USD/JPY
100.622
100.641
which is correct and what I would like it to be displayed on my webpage.However when I pass the data to my Servlet
try {
ArrayList<select.rates> rates = example.caseGetRates();
for(int i=0;i < rates.size();i++){
System.out.println("");
System.out.println(rates.get(i).getPair());
System.out.println(rates.get(i).getBid());
System.out.println(rates.get(i).getAsk());
}
request.setAttribute("rates", rates);
}
request.getRequestDispatcher("/NewFile.jsp").forward(request, response);
The result I get on my Servlet is:
USD/JPY
100.622
100.641
USD/JPY
100.622
100.641
The result does loop twice however the data seems to be overwritten and I still can't figure out why is this happening. I hope someone can pin point my mistake.
Create ArrayList object outside for loop
and inside for loop create new Object that you are adding to ArrayList
try {
ArrayList<select.rates> rates = example.caseGetRates();
for(int i=0;i < rates.size();i++){
// create new object here and then add to ArrayList
}
request.setAttribute("rates", rates);
}
request.getRequestDispatcher("/NewFile.jsp").forward(request, response);

Is there anything wrong in these two methods that copy & returns an array

Is there anything wrong in these two methods that copy & returns an array?
This is how i called it :
o2[i].addArr(o1.getArr());
And at the end the result is that o2[i].getArr(); is empty. I don't know why but this is my code if you could help me
NOTE: The class Array i wrote it here Array while it's another class name in my code. just to make it clear for you
public Array[] getArr(){ //first method
int count=0;
for(int i=0;i<10;i++){
if(Arrlist[i]!=null)
count++;}
Array[] arr=new Array[count];
for(int i=0;i<count;i++)
arr[i]=Arrlist[i];
return arr;}
public void addArr(Array[]arr){ //second method
for(int i=0;i<arr.length;i++)
Arrlist[i]=arr[i];
}
Yes. In getArr, you're going to overrun the length of the array you're creating if you have any null entries in the array you're copying.
In the loop where you're actually copying, you need separate variables for the index into arr and the index into Arrlist, because you need to skip nulls.
E.g., along these lines (untested):
int i, j;
j = 0;
for (i = 0; i < Arrlist.length; ++i) {
if (Arrlist[i] != null) {
arr[j++] = Arrlist[i];
}
}
addArr is okay if (and it's a big "if") Arrlist is allocated and it's the same size as arr. (You could replace it with System.arraycopy.) Note that the name is misleading, though; you're overwriting Arrlist, not adding to it. And again, those are some pretty big "if"s.

Why do I get a "duplicate local variable" error?

I have a loop in which I calculate a value and add it it a list. So, I do something like that:
x = getValue()
values.add(x)
while (true) {
x = getValue();
values.add(x)
}
I found out that this approach does not work since I add the same instance to the list. In more details, in every cycle of the loop I re-assign a new value to the x and doing so I change values of all elements that were already added to the list (so in the end I get a list of identical elements).
To solve this problem I did the following:
x = getValue();
Integer[] valueToAdd = new Integer[n];
for (int i=0; i<n; i++) {
valueToAdd[i] = x[i];
}
while (true) {
x = getValue();
y = new Integer[n];
for (int i=0; i<n; i++) {
valueToAdd[i] = x[i];
}
values.add(valueToAdd)
}
In this way I wanted to create a new instance every time want to add a value to the list. But it does not work since I get a duplicate local variable error.
It is also strange to me that I do not have this error if I declare the same variable many times in the loop. The problem appears only if I first declare a new variable outside the loop and then also in the loop.
Is there a way in Java to re-use the same name for different instances?
ADDED
I need to clarify some issues. I did not show all the code. I have the break command in the loop (when a new value cannot be generate, I exit the loop). x and value have Integer[] type.
ADDED 2
Since it was mentioned that the problem can be in the getValue() I need to in more details here. Actually I do not have getValue() in my code (I used getValue() here to make my example shorter). In my code I had:
Integer[] x = new x[n];
while (true) {
for (int i=0; i<n; i++) {
x[i] = y[i];
}
values.add(x)
}
And it did not work since in my values list I had identical elements (and I know that in the loop on every cycle x had a new value).
ADDED 3
Why all elements of my list seems to be the same?
Your problem is not what you think it is. For example take a look at this simple program:
String x = null;
List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i ++) {
x = String.valueOf(i);
l.add(x);
}
System.out.println(l);
It prints the numbers from 0 to 9. This is because java is pass-by-value (check here). You are not passing the reference to x, you are passing the value of x (in the add method).
So the problem lies in the getValue() method, which returns the same object.
Update: Now the question makes more sense. You are working with the same object x everytime, and just changing its state. In order to put different values just move the declaration inside the loop:
while (true) {
Integer[] x = new x[n];
...
}
If you need it outside the loop, well, simply use another variable there. It does not have to be named x. Since you won't be using it inside the loop anyway.

Categories