java array declaration - java

I get the error shown in the comment when I call my class's constructor
(when I remove the array parts everything goes fine). Is this because of a wrong declaration of the array seq?
public class FibIt implements SeqIt{
public int counter;
public int ptr;
public int [] seq;
public FibIt(Fib x)
{ counter=0;
ptr=0;
seq[0]=x.first1; //gives me an error here saying Exception in
//thread "main" java.lang.NullPointerException
//at FibIt.<init>(FibIt.java:9)
//at Main.main(Main.java:6)
seq[1]=x.first2;
for (int i=2; seq[i-1]<=x.last; i++)
{seq[i]=seq[i-1]+seq[i-2];}
}
#Override
public int func2() {
// TODO Auto-generated method stub
ptr++;
return seq[ptr-1];
}
}

You have to initialize your array, so something like public int[] seq = new int[10];
Then replace 10 with whatever size you need.
And I was just about to answer your question when #Jack posted a good solution. ArrayList<Integer> is pretty useful if you don't know the size of the array.

You need to initialize the array. One thing is declaration, other thing is inizialization.
int[] seq declares a variable of name seq which is an array of int. Then you need to effectively inizialize it by assigning to it a constructor for an array: new int[dimension]

Yes, you have only declared the array but not initilized.
public int [] seq = new int[anySize];

Related

Returning contents from an Array

I try to assign an array of numbers from 1 to 10 using the code below. Basically I am stuck on how to return an array. Do I need a toString method ?
package arrays1;
import java.util.Arrays;
public class Arrays1 {
/**
* #param args the command line arguments
*/
private int[] numbers;
private int DEFAULT_SIZE = 10;
public Arrays1(int size){
numbers = new int[DEFAULT_SIZE];
}
public int[] add(int[] n)
{
for(int i=0; i<numbers.length; i++){
numbers[i]=n[i];}
return numbers;
}
public int[] getValues(){
return numbers;
}
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
System.out.println(A.getValues());
}
}
How do I return contents of an array from this code? Do I need to create a new object?
A.getValues() is returning a pointer to the integer array numbers object, which is probably the output you're seeing. You don't need a new object, just use the one you made, Arrays1 A, and iterate over its contents, so something like this:
public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);
for (int i = 0; i < A.getValues().length; i++){
System.out.println(A.numbers[i]);
}
}
Yes, a toString method would be useful to serialize the contents of the numbers array to a String. But in this case, you should call it like this:
Arrays1 a = new Arrays1(9);
System.out.println(a); // it is an implicit call to toString()
Another acceptable alternative is to let the serialization to the client's responsibility. In this case, the client should rely on the getValues() method, and serialize it by itself:
Arrays1 a = new Arrays1(9);
System.out.println(Arrays.toString(a.getValues()));
Another lesser detail: Review your constructor: It does not use the parameter size, and that can be confusing.

How do I make an array parameter in java?

I tried to make a parameter for an array for a method, but it always comes up with an error.
public void methodExample1() {
int array1[] = new int[4]
}
public void methodExample(Array array1[]) {
System.out.println(array1[0]);
}
But it always says there's an error in my parameter. Is there any way to do this?
Try this:
public void methodExample(int[] array1)
Explanation: The type is the same that you used for declaring a value that will be passed as parameter (for the moment I'm ignoring covariant arrays), for instance if you do this:
int[] array1 = new int[4];
... Then, at the time of passing it as a parameter we'll write it like this:
methodExample(array1)
Also notice that the size of the array must not be passed as parameter, and that by convention the [] part goes right after the type of the array's elements (in fact, int[] is the type of the array), and not after the array's name.
If I understand your question, then you could use Array, and something like
public static void methodExample(Object array1) {
int len = Array.getLength(array1);
for (int i = 0; i < len; i++) {
System.out.printf("array1[%d] = %d%n", i, Array.get(array1, i));
}
}
public static void main(String[] args) {
methodExample(new int[] { 1, 2, 3 });
}
Output is
array1[0] = 1
array1[1] = 2
array1[2] = 3
I assume that you are trying to pass array as a parameter to a method , to initialize it and then call another method to print it?
In java you have to create an object and "allocate" memory space for it by calling to new ...
so you can do like that :
public static void main(String[] args) {
int [] m_array; // creating a array reference
m_array = new int[5]; // allocate "memory" for each of of them or you can consider it as creating a primitive of int in each cell of the array
method(m_array); // passing by value to the method a reference for the array inside the method
}
public void method(int [] arr) // here you are passing a reference by value for the allocated array
{
System.out.println(arr[0]);
}

Adding numbers to arrays with methods in another class?

I am learning java and trying to figure out how to implement these methods into my main class from a second class. The program takes user input to add numbers into an array and then I need to print the following using the pre-specified methods below. The parameters in the below method is what confuses me.
public static double findMin(double[] numbers, int count) //count is the count of numbers stored in the array
public static double computePositiveSum(double[] numbers, int count)
public static int countNegative(double[] numbers, int count)
Basically, I am confused as to how I link all the variables and array between the two classes so they can recognize the parameters and return the correct value to output min, sum and number of negatives. Do I want the array in the main method?
Basically, what I did now to fix it was that I created the variables in the main method and then pass the variables in the main method through the parameters of the object I created that links to the secondary class. Does that seem ok?
If you already have the array , so what you need is call your methods and pass this value to it
lets say you have this array :
double[] num = {1.2,2.3};
and your count is the length of num array , so the count is:
int count = num.length;
then call your method and pass the parameters to it like this:
findMin(num , count );
computePositiveSum(num , count );
countNegative(num , count );
Note : you need to read in Object-Oriented Programming Concepts
Sorry guys for such a question. I just needed a refresher since it has been awhile. I resolved the issue by creating the array and count variable in the main method and then passed those through the parameters so the methods in the secondary class could read them. Thanks for the quick responses and help .
You don't need a count variable, you can use myarray.length
So your code should be something like this:
public static void main(string [] args)
{
double[] myarray = {5.3, 69.365, 125, 2.36};
double result = MyClass.findMin(myarray);
}
public class MyClass
{
public static double findMin(double[] numbers)
{
// your impl
}
public static double computePositiveSum(double[] numbers)
{
// your impl
}
public static int countNegative(double[] numbers)
{
// your impl
}
}
You can create an object reference of the main class in your derived class. Then call these methods using the object of your main class.
class Main
{
------
}
class derived
{
Main m = new Main();double[] A=new double[1];
Scanner s = new Scanner(System.in);
int i=0,wc=1;
int arrayGrowth=1;
while(s.hasNext())
{
if (A.length == wc) {
// expand list
A = Arrays.copyOf(A, A.length + arrayGrowth);
wc+=arrayGrowth;
}
A[i]=s.nextDouble();
i++;
}
int len=A.length-1;
m.findMin(A,len);
m.computePositiveSum(A,len);
m.countNegative(A,len);
}

Accessing arrays with methods

Hi guys i'm just starting to learn Java, and I wondering how can I access an array that was declared in a method from another method?
The design look like this:
public class Arrays{
int arraysize = 2;
public void initializeArray(){
float array[] = new float[arraySize]; // Declare array
}
public void accessArray(){
// I want to access the array from this method.
}
}
Read about scope of variables in java. This is link I could find on quick Google search. http://www.java-made-easy.com/variable-scope.html
You can declare the array at class level then it is accessible in all methods.
public class Arrays {
int arraysize = 2;
private float[] array = null;
public void initializeArray() {
array = new float[arraySize]; // Declare array
}
public void accessArray() {
// access array here.
}
}
Or You can pass the variables in method.
public class Arrays {
int arraysize = 2;
public void initializeArray() {
float[] array = new float[arraySize]; // Declare array
accessArray(array);
}
public void accessArray(float[] array) {
// access array here.
}
}
Given the amount of information, I have from question, approach 1 seems better than 2.
You need to move your declaration to make it a member, otherwise it will go out of scope once the initializeArray call ends. Then you can access the array from both methods. Try this:
public class Arrays{
float[] array;
int arraysize = 2;
public void initializeArray(){
array = new float[arraySize]; // Declare array
}
public void accessArray(){
array[0] = 1.0f;
}
}
This is done thusly
public class myClass{
int arraysize = 2;
float[] myArray; // Declare array
public myClass(){
myArray = new float[arraySize]; // initialize array
}
public float[] accessArray(){
return myArray;
}
}
The array declaration must not be done inside the class methods.
Variable declaration done inside a method limits it's scope of a variable to the method. (i.e you can't use it anywhere else).
The array is then instantiated in a constructor.
A constructor is a special function that is run when a class is instantiated.
Constructor are used to instantiated a class's variables
Constructors have the same name as their class and must not specify a return type (so no public int or public void just public)
Next you need to change the return type of the accessArray method. A return type of void states that the method isn't going to return anything. Change it to float[]
Then your accessArray method need only return the array variable.
EDIT: The
"return myArray;"
line of code gives a reference to the array to what ever called the function (Not a copy of the array, the actual array, a quick of Java is that it always does this except when returning primitive data types where it returns a copy)
If you want accessArray() to set floats in the array instead of returning the array it should be implmented like this.
public void accessArray(int index, float value){
myArray[index] = value;
}
There a two options:
You declare that array as instance variable
public class Arrays {
private int arraySize = 2;
private float array[];// Declare array
public void initializeArray() {
array = new float[arraySize];
}
public void accessArray() {
// I want to access the array from this method.
float first = array[0];
}
}
You pass the array as parameter to the method (resp. the initializeArray method should return an array)
public class Arrays {
public static void main(String[] args) {
int arraySize = 2;
float[] array = initializeArray(arraySize);
accessArray(array);
}
public static float[] initializeArray(int size) {
return new float[size];
}
public static void accessArray(float[] floats) {
// I want to access the array from this method.
float first = floats[0];
}
}

'This method must return a result of type int' Java?

public static void main(String args[])
{
double arr[] = {1,-6.3,9000,67.009,1.1,0.0,-456,6,23,-451.88};
ArrayList<Integer> List = new ArrayList<Integer>();
List.add(1);
List.add((int) -6.3);
List.add(9000);
List.add((int) 67.009);
List.add((int)1.1);
List.add((int)0.0);
List.add(-456);
List.add(6);
List.add(23);
List.add((int)451.88);
}
public static int ArrayListMax(ArrayList List)
{
for (int i=0; i<List.size(); ++i)
{
System.out.println(List.get(i));
}
The error is in:
public static int ArrayListMax(ArrayList List)
This is probably a very nooby mistake, but I'm new to Java so forgive me.
Any help please?
Thank you.
EDIT:
I want the ArrayListMax method to print the size of the List!
Assuming you are trying to get the maximum value in your List in the method arrayListMax, you need to return an integer in accordance with your method signature, which the error is telling you
This method must return a result of type int
Instead of printing all the values in the list, you could do:
public static int arrayListMax(List<Integer> List) {
return Collections.max(list);
}
Use Java Naming Conventions. Method & variable names begin with a lowercase letter. Using this approach helps avoid confusion between instances & types (e.g. in the case of List in the main method).
Either add a return statement to your ArrayListMax() method that returns an int or change the method signature from public static int to public static void. And add a closing } to the method too.
Also, you shouldn't use List as a name for the argument to that method because it's the name of an interface that you're actually importing in this code. The convention in java is for variable names and method names to begin with a lowercase letter (camel case) and class names to begin with an uppercase letter (pascal case).
Problem is in this method:
public static int ArrayListMax(ArrayList List)
{
for (int i=0; i<List.size(); ++i)
{
System.out.println(List.get(i));
}
}
You are not returning from this method, you must return of type int to solve that error. Since you have specified int as return type.
You created the function as returning a result
public static int ArrayListMax(ArrayList List)
In order to remove your problem, if you need not return anything, write
public static void ArrayListMax(ArrayList List)
void means you do not want the method to return a result.
if you are just printing out values the signature should be public static void ArrayListMax(ArrayList List).
First, you are not returning anything with ArrayListMax method even if you have set its retun type to int. Either return void as you are directly printing from the list.
Second, even if you set the correct return type to ArrayListMax method, you will still need to call that method in the main method as below:
public static void main(String args[])
{
double arr[] = {1,-6.3,9000,67.009,1.1,0.0,-456,6,23,-451.88};
ArrayList<Integer> List = new ArrayList<Integer>();
List.add(1);
List.add((int) -6.3);
List.add(9000);
List.add((int) 67.009);
List.add((int)1.1);
List.add((int)0.0);
List.add(-456);
List.add(6);
List.add(23);
List.add((int)451.88);
YourClassNameInWhichMethodIs.ArrayListMax(List);
}
You should use a return statement as Methode is returning an int type value.

Categories