How to I call a method to create arrays from another class? - java

So I have this code in the main class
public class OneDArrays
{
public static int[] create (int size)
{
int[] a1 = new int[size];
for (int i = 0; i < size; i++)
{
a1[i] = i*2+1;
}
return a1;
}
public int sumSome (int[] b1, int howmany)
{
int sum = 0;
if (howmany <= b1.length)
{
for (int i = 0; i < howmany; i++)
{
sum = sum + b1[i];
}
}
else
{
sum = -1;
}
return sum;
}
public int[] grow (int[] c1, int extra)
{
int[] newArray = new int[c1.length+extra];
for (int i = 0; i < newArray.length; i++)
{
while (i <= c1.length)
{
newArray[i] = c1[i];
i++;
}
newArray[i] = 0;
}
return newArray;
}
public void print (int[] d1)
{
for (int i = 0; i < d1.length; i++)
{
System.out.println (d1[i] + ", ");
}
}
}
And then I have my tester class,
public class OneDArraysTester
{
public static void main (String[] args)
{
int[] test1;
test1.create (5);
}
}
How do retrieve the method from the first class? I get the error that "create" is an undeclared method. If the "create" method were a constructer, I know I could just type create test1 = new create (5) but I don't see a way to turn it in to a constructer, so what's the way of doing that but for a method?

You invoke a static method with the classname. Literally className.methodName. Like,
int[] test1 = OneDArrays.create(5);

You have made a class named OneDArrays so you can call it's methods by creating an instance or object of that class.
like this :
OneDArrays ObjectOfClass = new OneDArrays();
int test1[] = ObjectOfClass.create(5);
similarly you can also call other methods of that class by accessing methods of this newly created object ObjectOfClass.
like :
sumOfArray = ObjectOfClass.sumSome(test1,3);
int biggerTest1[] = ObjectOfClass.grow(test1,10);
If you want to make create method works as a constructor than you can but you cannot return value from a constructor so you cannot return your array from that constructor.

Since you have declared the create method as static, #ElliotFrisch is the best way. But, it is not always a good idea to make methods static. So another way to achieve what you want would be to make the create method non-static.
public int[] create (int size){/*Method Body*/};
And then create an object of the OneDArray class to access the method.
OneDArrays oneDArrays = new OneDArrays();
int[] test1 = oneDArrays.create(5);
or,
int[] test1 = new OneDArrays().create(5);

Related

Array Method issue

having a problem with my java program. I am a newbie to Java and just can't figure out what is exactly the issue with it. In short I've declared an array and a variable in main, I've created my method call and would like my array be passed into my method with the variable. I would then like the method to take my array and count the number of times my variable "8" occurs, get rid of the 8 out of the array and return a new smaller array back to main. Here is my code below. I feel as if I am just missing one block code any suggestions?
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < arrayA.length; x++)
{
System.out.print(arrayA[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
}
}
return arrayX;
}
}
you do not actually need to return the array because when you pass an array to a method you also pass its memory address meaning its the same address that you change so, it will also change the arraysA of main method because you are just changing the values of the same memory adress
import java.util.*;
public class Help
{
public static void main(String[] args)
{
ArrayList<Integer> arraysA = new ArrayList<Integer>();
arraysA.add(Integer.valueOf(2));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(19));
arraysA.add(Integer.valueOf(32));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(18));
arraysA.add(Integer.valueOf(25));
arraysA.add(Integer.valueOf(17));
arraysA.add(Integer.valueOf(8));
arraysA.add(Integer.valueOf(3));
arraysA.add(Integer.valueOf(4));
arraysA.add(Integer.valueOf(8));
int varB=8;
newSmallerArray(arraysA,varB);
for(Integer i:arraysA)
{
System.out.println(i);
}
}
public static void newSmallerArray(ArrayList<Integer> arraysA,int varB)
{
for(int i=0;i<arraysA.size();++i)
{
if(Integer.valueOf(arraysA.get(i))==varB)
{
arraysA.remove(i);
}
}
}
}
Try this code it will not require for loop:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(arrayA));
list.removeAll(Arrays.asList(8));
arrayA = list.toArray(array);

Visibility Control of the variables

package Array;
public class ArrayLesson1
{
static int[] array = { 10, 20, 30, 40 };
public static void main(String[] args) {
int i = 0;
System.out.println("While Loop Result");
while (i < 4) {
int c = array[i] * array[i];
System.out.println("Resutl = " + c);
i++;
}
subclass obj = new subclass();
obj.loopj();
obj.loopk();
}
}
class subclass {
public static void loopj() {
for (int j = 0; j < 4; j++) {
int result = array[j] * array[j];
System.out.println("FOR Loop J Result");
System.out.println("Result = " + result);
}
}
static void loopk() {
for (int k = 0; k < 4; k++) {
int result2 = array[k] + array[k];
System.out.println("FOR Loop K Result");
System.out.println("Result = " + result2);
}
}
}
From the above code, I couldn't access the "array" from the class "ArrayLesson1".
Below you can find the Output:
While Loop Result
Resutl = 100
Resutl = 400
Resutl = 900
Resutl = 1600
I am getting below error.
Exception in thread "main" java.lang.Error: Unresolved
compilation problems: array cannot be resolved to a variable array
cannot be resolved to a variable
at Array.subclass.loopj(ArrayLesson1.java:40)
at Array.ArrayLesson1.main(ArrayLesson1.java:25)
You have declared array in your ArrayLesson1 class, which is not visible to your subclass so you are getting compilation error.
You have couple of options,
1) Create constructor in your subclass to accept array as an argument and create a local variable in your subclass and pass array from ArrayLesson1 to your subclass like this:
//in subclass
private int [] array;
public subclass(int [] array) {
this.array = array;
}
So call like this in your ArrayLesson1 class like this:
subclass obj=new subclass(array); // Pass array like this
2) Modify loopj() and loopk() method to accept array as a parameter like this:
public static void loopj(int [] array) {
//Codes here
//
and call it in your ArrayLesson1 like this:
obj.loopj(array);
3) Or if you want to use static reference then you need to use with classname.variablename before using it, like this:
ArrayLesson1.array[j]
Let me know if this helps.

Java: How to use functions of a class which has been instantiated by ArrayList

Here is just a simple example. Obviously there are simpler ways to set everything up within the constructor, but the arrayList I'm actually working with has already been set up, I just need to change individual sections of it. There HAS to be a way to call a class's functions in ArrayList, but for the life of me I can't figure out how.
import java.util.ArrayList;
public class ArrayTest{
public static void main(String[] args){
//Here's an example of a regular array:
Length[] lArray = new Length[3];
for (int i = 0; i < 3; i++){
lArray[i].setLength(i + 1);
}
//Here's how I was hoping ArrayList would function:
ArrayList<Length> lList = new ArrayList<Length>(3);
for (int i = 0; i < 3; i++){
lList[i].setLength(i + 1);
// --OR--
lList.setLength(i, i + 1);
}
}
}
Here's the length class:
public class Length{
private int length;
Length(){
length = 0;
}
Length(int s){
length = s;
}
public void setLength(int s){
length = s;
}
}
Thanks!
You add elements to the ArrayList with add.
Since it's an ArrayList<Length>, you add Length objects:
lList.add(new Length());
And in your specific loop :
ArrayList<Length> lList = new ArrayList<Length>(3);
for (int i = 0; i < 3; i++){
Length l = new Length();
l.setLength(i+1);
lList.add(l);
}
BTW, the array initialization is also missing an important initialization :
for (int i = 0; i < 3; i++){
lArray[i] = new Length(); // added
lArray[i].setLength(i + 1);
}
If the ArrayList already contains the elements, and you just want to modify them, you can write something like this:
lList.get(i).setLength(i + 1);
assuming that the ArrayList contains the ith element.
You could create a method with your operation/algorithm like
public void foo(){
System.out.println("some algorithm!");
}
inside Length class. This will operate on each instance of Length class.
And for iterating, you can use
ArrayList<Length> lList = new ArrayList<Length>(3);
for (Length l : lList){
l.foo();
}
This will call everything you code inside foo.

non-static variable this cannot be referenced in a static context in Java

I don't understand why does this code give me issues since I am declaring new instances within the outclass.
Here is my solution for the problem (UvA-103): 103-StackingBoxes.
Originally I was getting runtime errors of NullPointerExceptions:
C:\Users\User\Desktop\103-StackingBoxes>java
Main
5 2
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:27)
I fixed that, but now I am getting the following compilation error:
C:\Users\User\Desktop\103-StackingBoxes>javac
Main.java
Main.java:28: error: non-static variable this cannot be referenced from a static
context
boxArray[i] = new box();
^
1 error
I know inner classes are typically avoided in Java, but I do not get why in particular do my statements not work.
import java.util.*;
import java.io.*;
//import java.util.Arrays;
public class Main
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int k,n;
while(input.hasNext())
{
System.out.printf("\n");
k = input.nextInt();
n = input.nextInt();
// box boxArray[] = new box(n)[k];
box[] boxArray = new box[k];
for(int i =0; i< k; i++)
{
boxArray[i] = new box();
//boxArray[i] = boxArray[i].box(n);
boxArray[i].totalDim = n;
for(int j =0; j < n; j++)
{
boxArray[i].dimensions[j]=input.nextInt();
}
}
boxArray = sortBoxArray(boxArray);
int count = 1;
for(int i =k-1; i > 1 ; i--)
{
if(boxArray[i].doesArgBoxFitInside(boxArray[i-1]))
count++;
else
break;
}
System.out.printf("%d\n",count);
for(int i = k-count; i < k ; i++)
{
if(i == k-1)
System.out.printf("%d",boxArray[i].placeNumber);
else
System.out.printf("%d ",boxArray[i].placeNumber);
}
}
}
public static box[] sortBoxArray(box[] boxArray)
{
for(int i = 1; i < boxArray.length; i++)
{
for(int j = boxArray.length-1; j>=i; j++)
{
boolean skip = false;
for(int k = 0; k < boxArray[j].totalDim; k++)
{
if(boxArray[j].dimensions[k]<boxArray[j].dimensions[k-1])
{
box temp = boxArray[j-1];
boxArray[j-1] = boxArray[j];
boxArray[j]=temp;
}
}
}
}
return boxArray;
}
public class box{
/*******************************************Fields***********************************************/
public int totalDim;
public int dimensions[];
//The field I forgot about
public int placeNumber;
/*******************************************Methods**********************************************/
public box()
{
this.totalDim = -1;
this.dimensions= new int[0];
this.placeNumber = -1;
}
public box(int totalDim)
{
this.totalDim = totalDim;
this.dimensions = new int[totalDim];
}
//public box(int totalDim, int[totalDim] dimensions)
public box(int totalDim, int[] dimensions)
{
this.totalDim = totalDim;
this.dimensions = dimensions;
sortDim();
}
public void sortDim()
{
Arrays.sort(dimensions);
}
public boolean doesArgBoxFitInside(box wop)
{
if(this.totalDim != wop.totalDim)
return false;
else
{
for(int i =0; i < totalDim; i++)
{
if(this.dimensions[i]<wop.dimensions[i])
return false;
}
return true;
}
}
}
}
Your class box (please stick to Java's coding conventions of uppercase class names!) is an inner class and not visible for your static code:
"An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();"
(http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html).
Problem is: Your box class is inner class of Main class, As pointed by #Smutje that inner class is not visible to static method. Reason for this is: static method can be executed even if there is no instance of class and inner class object can only exist if there is object of outer class, so both statement are sort of contradictory. Hence, inner class is not made directly accessible in static method.
Fix:
Either you can make Box class as static or you can make an instance of Box class after making object of outer class.
Code for second solution:
Main obj = new Main();
for(int i =0; i< k; i++)
{
boxArray[i] = obj.new box();

removing a column from a 2d array

I am trying to write a class that will remove a column from a 2d array, but I keep running into errors that I don't understand. I think I am misunderstanding something very basic here, any help would be appreciated
public class CollumnSwitch
{
int[][] matrix;
int temp;
public static void coldel(int[][] args,int col)
{
for(int i =0;i<args.length;i++)
{
int[][] nargs = new int[args.length][args[i].length-1];
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
int temp = args[i][j];
}
nargs[i][j]= temp;
}
}
}
public void printArgs()
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j]);
}
System.out.println();
}
}
}
You cannot access a non-static variable from a static context, you need to change int temp; to static int temp; or you can remove static from your method declaration.
You declare your nargs array in the coldel method, so it is not accessible from other methods. Meaning this doesn't work:
for(int i =0;i<nargs.length;i++) //You try to access nargs which is not possible.
{
for(int j =0;j<nargs[i].length;j++)
...
Maybe you want it to be the matrix array you have in your class? Like this:
in coldel:
matrix= new int[args.length][args[i].length-1];
and in printArgs
for(int i =0;i<matrix.length;i++)
{
for(int j =0;j<matrix[i].length;j++)
...
This require matrix to be static also (again, you can also remove static from coldel)
you can try like this:
static int[][] nargs;
public static void deleteColumn(int[][] args,int col)
{
if(args != null && args.length > 0 && args[0].length > col)
{
nargs = new int[args.length][args[0].length-1];
for(int i =0;i<args.length;i++)
{
int newColIdx = 0;
for(int j =0;j<args[i].length;j++)
{
if(j!=col)
{
nargs[i][newColIdx] = args[i][j];
newColIdx++;
}
}
}
}
}
public static void printArgs()
{
if(nargs != null)
{
for(int i =0;i<nargs.length;i++)
{
for(int j =0;j<nargs[i].length;j++)
{
System.out.print(nargs[i][j] + " ");
}
System.out.println();
}
}
}
Your difficulties are arising due to using variables outside of their scope. In java, variables basically only exist within the most immediate pair of braces from which they were declared. So, for example:
public class Foo {
int classVar; // classVar is visible by all code within this class
public void bar() {
classVar = classVar + 1; // you can read and modify (almost) all variables within your scope
int methodVar = 0; // methodVar is visible to all code within this method
if(methodVar == classVar) {
int ifVar = methodVar * classVar; // ifVar is visible to code within this if statement - but not inside any else or else if blocks
for(int i = 0; i < 100; i++) {
int iterationVar = 0; // iterationVar is created and set to 0 100 times during this loop.
// i is only initialized once, but is not visible outside the for loop
}
// at this point, methodVar and classVar are within scope,
// but ifVar, i, and iterationVar are not
}
public void shoo() {
classVar++; // shoo can see classVar, but no variables that were declared in foo - methodVar, ifVar, iterationVar
}
}
The problem you are having is because you are declaring a new 2-d array for each iteration of the for loop and writing one column to it, before throwing that away, creating a new array, and repeating the process.

Categories