sub class

public class Exer2
{

public void setLength(int x)
{
this.listLength=x;
}

public int getLength()
{
	return this.listLength;
}


int listLength=getLength();
int list[]=new int[listLength];

public void display()
{
System.out.println("The array length is: "+list.length+" ");
}

}

main class

import java.util.*;
public class Output
{
static Exer2 r=new Exer2();

public static void main(String[]args)
{
Scanner input=new Scanner(System.in);

int temp;

System.out.println("Enter array length: ");
temp=input.nextInt();
r.setLength(temp);
r.display();
}

}

I have a problem about inputting the array length.
the array length is always 0. no matter what number i input.
the length always remains to 0.
I am sure that my codings are correct, im just confused why it always displays 0.
any help is highly appreciated. thanks in advance.

Sample Output:

Enter array length:
100
The array length is: 0

Recommended Answers

All 6 Replies

My first guess is that when the object gets created it creates an array with the length (which is NULL / uninitialized at first).

Then when you do .setLength() it stores it in listlength but it doesn't do anything with it, because the array code is only run when you create the object.

When you use:

public void setLength(int x)
{
this.listLength=x;
// When it reaches this it goes back to MAIN.
}

Java simply puts a 'return' at the end of that function.

So this:

int listLength=getLength();
int list[]=new int[listLength];

*never* happens *after* the object is created.

One solution would be to establish a size before you create the object.

import java.util.*;
public class Output
{
   public static void main(String[]args)
   {
      Scanner input=new Scanner(System.in);
      int arraylength;
      System.out.println("Enter array length: ");
      arraylength=input.nextInt();
      Exer2 r=new Exer2(arraylength);
   }
}

Of course this would require you to edit the Exer2 class.

commented: This is correct. +1

i really dont know how to change the value of listLength.

my codes above. thats the only method I know to use.

can give an example on how to use this?

Exer2 r=new Exer2(arraylength);

i've added this to my Exer2 class but still nothing happens.
the output is still 0.

int listLength;

public Exer2()
{
listLength=10;
}

public Exer2(int listLength)
{
this.listLength=listLength;
}

public void setLength(int listLength)
{
this.listLength=listLength;
}

public int getLength()
{
	return this.listLength;
}

any help about this please

You're setting one variable and reading another.
The variable listLength is yours, list.length belongs to the array list . In your "setLength" method, you set listLength . If you add the line

System.out.println("The variable listLength is: "+listLength+" ");

to your display() method, you'll see that setting the one doesn't change the other.

The fact that you initialize your array to the value of listLength doesn't mean that the length changes when the variable does. At the time that initialization happens, listLength is zero (because you declared it and didn't initialize it to anything else, zero is the default) so your array is an array of length zero, and you have nothing in your code to change that.

---------------------
Slight digression: As it happens, nothing can change that: an array is an immutable object. You can't change its size after it's created, you can only change its contents or replace it with a different array. list is a variable, which holds a reference to an object in memory. The object in memory is an array, which is a data structure consisting of a number of contiguous addresses. The object that list has a fixed size which cannot be changed. list , the variable, can be changed: it can be set to point to a new array, with different contents or a different size or holding a different type.

Understand this, it's important.

---------------------

Return from digression: If you want to change the size of the array list to the value chosen by the user, you will have to initialize list again. This will lose anything the user might have stored in there. For the moment, I'll assume that this is okay with you, so just go ahead and assign list to hold a new int array of size x. When you've done that, your code will run as you expect. That is, your display() method will report that the length of list is whatever value you've entered at the command line.

thanks for the help. now here's my perfect code.

sub class

import java.util.*;
public class Exer2
{
int listLength;
int []list;

public Exer2(int l)
	{
	this.listLength=l;
	list=new int[listLength];
	}



public void displayLength()
{
	System.out.println("The array length is "+list.length+"\n");
}

public void insert1(int loc,int item)
{
list[loc]=item;
}

public void insert2(int item)
{
int x=0;
	while(x<list.length)
	{
		if(list[x]==0)
		{
		list[x]=item;
		x=list.length+1;
		}
	x++;
	}


}

public void display()
{
System.out.println("\nThe array contents: \n");
for(int x=0;x<list.length;x++)
{
System.out.print(" "+list[x]+" ");
}
System.out.println("\n\n");
}

public void selectionSort()
{
    int index;
    int smallestIndex;
    int minIndex;
    int temp;
    for (index = 0; index < listLength - 1; index++)
    {
        smallestIndex = index;
        for (minIndex = index + 1;
             minIndex < listLength; minIndex++)
            if (list[minIndex] < list[smallestIndex])
                smallestIndex = minIndex;

        temp = list[smallestIndex];
        list[smallestIndex] = list[index];
        list[index] = temp;
    }
}

public int seqOrderedSearch(int searchItem)
{
     int loc,not=0;

     for (loc = 0; loc < listLength; loc++)
     {
      if(list[loc]==searchItem)
      System.out.println("\n"+list[loc]+" can be found in the array\n\n");
      else
      not++;

      if(not==listLength)
      System.out.println("\nThe number you have entered is not in the array\n\n");
 	 }
return loc;
}


public void delete2(int item)
{
	for(int x=0;x<list.length;x++)
	{
	if(list[x]==item)
	list[x]=0;
	}
}

public void bigDiff()
{
int maxIndex = 0,minIndex=0,big=0,small=0,answer,index;
			for (index = 1; index < list.length; index++)
			{
			if (list[maxIndex] < list[index])
				maxIndex = index;
				big = list[maxIndex];
			if (list[maxIndex] > list[index])
				minIndex = index;
				small= list[minIndex];
			}
			answer=big-small;
System.out.println("\nThe difference of "+big+" and "+small+" is "+answer+"\n\n");
}

public void withoutTen()
{
int none=0;
	for(int x=0;x<list.length;x++)
	{
	if(list[x]==10)
	list[x]=0;
	else
	none++;

	if(none==list.length)
	System.out.println("\nThis array does not contain the number 10\n\n");
	}
}

public void tripleUp()
{
int first=0,second=0,third=0,one=0,two=0,three=0,none=0;
int x,temp,tempo;

	for(x=-1;x<list.length;x++)
	{
//0 1 2
		try
		{
			if(list[x]+1==list[x+1]&&list[x+1]+1==list[x+2])
			{
			first=list[x];      one=x;
			second=list[x+1];	two=x+1;
			third=list[x+2];    three=x+2;
			System.out.println("\nThe 3 increasing adjacent numbers are: \nlist["+one+"]: "+first+"\nlist["+two+"]: "+second+"\nlist["+three+"]: "+third+"\n\n");

			}
			else
			{
			none++;


			}
		}

		catch(Exception z)
		{

		}

	}

		if(none==list.length-1)
		{
		System.out.println("\nThere are no 3 increasing adjacent numbers in this array\n\n");
		}

}

}

MAIN CLASS

import java.util.*;
import java.io.*;
import java.text.*;
class Output
{

public static void main(String[]args)
{
BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
Scanner a=new Scanner(System.in);
int input=0,length,loc,item,search,limit=0;



try
{
System.out.println("Enter array length: ");
length=a.nextInt();
Exer2 r=new Exer2(length);
r.displayLength();


while(true)
{
display();
	try{
		input=Integer.parseInt(s.readLine());




		if(input==1)
		{
				System.out.println("\nInsert location and item");
				loc=Integer.parseInt(s.readLine());
				item=Integer.parseInt(s.readLine());
				r.insert1(loc,item);
				r.display();
		}


		else if(input==2)
		{
				System.out.println("\nInsert item only: ");
				loc=Integer.parseInt(s.readLine());
				r.insert2(loc);
				r.display();
		}


		else if(input==3)
		{
				System.out.println("\nEnter an item to delete: ");
				item=Integer.parseInt(s.readLine());
				r.delete2(item);
				r.display();
		}


		else if(input==4)
		{
				System.out.println("\nThe sorted array: ");
				r.selectionSort();
				r.display();
		}

		else if(input==5)
		{
			System.out.println("\nSearch an item");
			search=Integer.parseInt(s.readLine());
			r.seqOrderedSearch(search);
		}

		else if(input==6)
		{
			System.out.println("\nThe difference of the smallest and largest element");
			r.bigDiff();
		}

		else if(input==7)
		{
			System.out.println("\nRemove the 10's in the array");
			r.withoutTen();
			r.display();
		}

		else if(input==8)
		{
			System.out.println("\n3 increasing adjacent numbers: ");
			r.tripleUp();
			r.display();

		}

		else if(input==9)
		{
			System.out.println("\nGOOD BYE!");
			System.exit(0);
		}

		else
		{
			System.out.println("\nYou can only select numbers from 1=9\n");
		}

//seqOrderedSearch(int search)
	   }

	catch(Exception e)
		{
	System.out.print("Invalid input!!!\n\n");
		}
}

}

catch(Exception e)
{
	System.out.print("Invalid input!!\n\n");
}



}

public static void display()
	{
		System.out.print("WELCOME SCREEN :)\n");
		System.out.print("[1] - Insert location and item\n");
		System.out.print("[2] - Insert item only\n");
		System.out.print("[3] - Delete an item\n");
		System.out.print("[4] - Sort the array\n");
		System.out.print("[5] - Search an item\n");
		System.out.print("[6] - Difference of smallest and largest element\n");
		System.out.print("[7] - Remove the 10's in the array\n");
		System.out.print("[8] - Three increasing adjacent numbers\n");
		System.out.print("[9] - Exit\n\n");
	}
}

Thanks a lot.
that was one piece of the puzzle that really helped me finish everything.

i used these codes in declaring the array's length.
Thanks for the help

public Exer2(int l)
	{
	this.listLength=l;
	list=new int[listLength];
	}
Exer2 r=new Exer2(length);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.