Array Method issue - java

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);

Related

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

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);

How to initialize an Array object?

I'm having trouble initializing an Array and don't really understand how to do it.
public class Array {
int[] array;
public Array(int[] array) {
this.array = array;
}
public int sum() {
int sum = 0;
for (int i = 0; i < this.array.length; i++) {
sum = sum + array[i];
}
return sum;
}
public double average() {
double av = this.sum() / this.array.length;
return av;
}
public static void main(String[] args) {
Array a = new Array[3];
}
}
I keep getting an error that says required: Array found: array[]
I want to make a scanner and have user input on the array but I don't even know how to initialize it in the first place
You have to change
Array a = new Array[3];
To
Array a = new Array(new int[3]);
Constructor of Array is taking int[] as input arguments.

Issues with adding a random numbers to an array

I am trying to add random numbers to an empty array 20 numbers 0-99. When I run the code below it prints out 51 numbers and they are all 0.
Can someone please help me figure out what I am doing wrong here.
import java.util.Random;
public class SortedArray
{
int randomValues;
int[] value;
public SortedArray()
{
}
public int getRandom()
{
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues = random.nextInt(100);
}
return randomValues;
}
public int getArray()
{
int result = 0;
value = new int[randomValues];
for(int item : value)
{
System.out.println("The array contains " + item);
}
return result;
}
}
Here is my main method
public class ReturnSortedArray
{
public static void main(String[] args)
{
SortedArray newArray = new SortedArray();
int random = newArray.getRandom();
int array = newArray.getArray();
System.out.println(array);
}
}
In your method getArray
the code
value = new int[randomValues];
is simply creating a new empty int array of size ramdomValues.
As the default value of an int is 0, that is what you are getting
Also in your method getRandom you are setting the same value time and time again
for (...)
randomValues = random.nextInt(100);
try
public int[] getRandomArr()
{
int randomValues [] = new int [20];
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues[j] = random.nextInt(100);
}
return randomValues;
}
I see a few issues, you should probably set the values in your constructor. You could also call it a set method (since it's not actually a get). Also, your getArray() doesn't return an array. So, I think you really wanted something like this,
public class SortedArray {
private Random random = new Random();
private int[] value = new int[20];
public SortedArray() {
super();
setRandomValues();
}
public void setRandomValues() {
for (int j = 0; j < value.length; j++) {
value[j] = random.nextInt(100);
}
}
public int[] getArray() {
return value;
}
}
And then your main method, should be updated like
public static void main(String[] args) {
SortedArray newArray = new SortedArray();
int[] array = newArray.getArray();
System.out.println(Arrays.toString(array));
}

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.

Beginner: Assigning values to arrays in Java

I am attempting to write a simple Genetic Algorithm in Java after reading a book on Machine Learning and have stumbled on the basics. I'm out of practice with Java so I'm probably missing something extremely simple.
Individual
public class Individual {
int n;
int[] genes = new int[500];
int fitnessValue;
public int getFitnessValue() {
return fitnessValue;
}
public void setFitnessValue(int fitnessValue) {
this.fitnessValue = fitnessValue;
}
public int[] getGenes() {
return genes;
}
public void setGenes(int index, int gene) {
this.genes[index] = gene;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
// Constructor
public Individual() {
}
}
Population
import java.util.Random;
public class Population {
public Population() {
}
public static void main(String[] args) {
Random rand = new Random();
int p = rand.nextInt(10);
int n = rand.nextInt(10);
Individual pop[] = new Individual[p];
System.out.println("P is: " + p + "\nN is: " + n);
for(int j = 0; j <= p; j++) {
for(int i = 0; i <= n; i++) {
pop[j].genes[i] = rand.nextInt(2);
}
}
}
public void addPopulation() {
}
}
The aim of this code is to populate the Population and the Genes with a random number. Could someone please take a look at my code to see where I'm going wrong?
before
pop[j].genes[i] = rand.nextInt(2);
add
pop[j] = new Individual();
the elements of the array are null.
I believe you need to initialize pop[j] before doing pop[j].genes[i] = rand.nextInt();
Individual pop[] = new Individual[p];
This just initializes the array, not the individual elements. Try to put pop[j] = new Individual() between your two loops.
What they said...
Also, do you mean to call your setGenes method, or do you just want to directly access the gene array.
From what I understand of your code I think you need to do this:
for(int j = 0; j <= p; j++) {
pop[j] = new Individual();
for(int i = 0; i <= n; i++) {
pop[j].setGenes(i, rand.nextInt(2));
}
}

Categories