Filling an array using a method [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I'm stuck with a revision question from a lab. The question is:
Write a static method to initialize an array of integers called numList. The size of the array should be passed as an int to the method and the array should be returned. Each odd index position should contain the value -1 and each even numbered position should contain the index value. Thus, such an array might contain {0,-1,2,-1,4,-1,6,-1}.
My code is currently :
public class initializeArray{
public static void main (String [] args) {
int [] numList = new int [6];
alterArray(numList);
}
public static void alterArray (int [] numList)
{
for( int i = 0; i<numList.length; i++)
{
if (i == 0)
{
numList[i] = i;
} else{
numList[i] = -1;
}
}
System.out.println( "The array is: " + numList);}
}
The return that I'm getting is :
"The array is: [I#1ef856c"
Thanks.
Updated to:
System.out.println(Arrays.toString(numList));
Error now occuring:
"Cannot find symbol - variable Arrays"

Try this:
System.out.println(Arrays.toString(numList));

Related

Why is Java giving my ArrayList an IndexOutOfBoundsException? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
Why is Java giving me an error message?
Im using JavaSE-12 and don't understand why I have an IndexOutOfBoundsException.
Do I have to specify the index of the ArrayList or what am I missing?
import java.util.ArrayList;
public class DSArrayList {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> namensListe = new ArrayList<String>();
namensListe.add("Hans");
namensListe.add("Peter");
for(int i = 0; i <= namensListe.size(); i++) {
System.out.println("Name: " + namensListe.get(i));
}
}
}
for(int i = 0; i < namensListe.size(); i++)
(note the < operator)
To explain, arrays and like structures are indexed from zero, not one. Obviously we count, however, from one, not zero. So the length of an array is always one greater than the index of the last item it contains.

Java: How to create an array object with a constructor? [duplicate]

This question already has answers here:
When do you use varargs in Java?
(8 answers)
Closed 4 years ago.
I could use help/direction on how to build a constructor that receives (for example 1, 2, 3) int's and stores them into an array object called arr2.
Part I:
public static void main (String[] args) {
Create an Arrays object using the first constructor
Arrays arr1 = new Arrays(5);
Arrays arr2 = new Arrays (1,2,3);
}
Part II:
public class Arrays {
private int [] array;
private int count;
public Arrays(int[] arr){
int[] array = arr;
array= arr;
count = arr.length;
}}
You could do it like this:
public class Arrays {
private int [] array;
public Arrays(int... arr){
array = arr.clone();
}
public int get(int index) {
return array[index];
}
}
Changes from your code:
The constructor uses varargs (look it up).
There is no need to store the count; if you want the count the count, use array.length().
The array is copied. This means you can change the original array that you passed in, but the values in the Arrays object won't be affected.
I've added a getter method.
Try use this constructor with var args
public Arrays(int... arr) {
int[] array = arr;
array= arr;
count = arr.length;
}

My array gives me a list of random letters, symbols and numbers [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
I am trying to create a program that takes a array of 7 random numbers from 1-10 and puts them in a array and prints it,but whenever I run it I get this same result [I#6d06d69c.
import java.util.Random;
public class DiversCalc {
public static void main(String[] args){
int[] myList = new int[7];
Random rand = new Random();
for (int positionInArray = 0; positionInArray < myList.length;
positionInArray++) {
int diverScore1 = rand.nextInt(10);
myList[positionInArray] = diverScore1;
}
System.out.println(myList);
}
}
System.out.println(myList); is evaluated like myList.toString() and it will only print out the memory address which you are getting ([I#6d06d69c).
So, you should use Arrays.toString() to print array for per item;
System.out.println(Arrays.toString(myList));

java generics: defining objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to learn Java and having trouble understanding generics. I'm attempting to define an object of Integer data type, then use the object to to call a generic method.
Guided by the API and some web resources, I've been trying all sorts of things but I don't know if i'm on the right track in terms of simply defining the object.
SearchSortAlgorithms.java:
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
public void quickSort(T[] list, int length)
{
recQuickSort(list, 0, length - 1);
}
}
TestQuickSort.java
public class TestQuickSort
{
static void main(String [] args)
{
// define an Integer array of 50000 elements
Integer[] anArray = new Integer[5000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*50000)
for (int i = 0; i < anArray.length; i++) {
anArray[i] = (int)(Math.random() * i);
}
// define an object of SearchSortAlgorithm with Integer data type
// use this object to call the quickSort method with parameters: your array name and size-50000
Integer aSortedArray = new Integer(5000);
public void quickSort(anArray, 5000) {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
return aSortedArray.quickSort(anArray, 5000);
}
// print out the first 50 array elements with a for loop
// they have to be sorted now
for (int k = 0; k <= 50; k++) {
System.out.print(aSortedArray[k] + " ");
}
}
}
Errors on these lines:
public int TestQuickSort () {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
aSortedArray = quickSort(anArray, 5000);
}
-Illegal start of expression: I wonder if my attempt at creating the constructor is right
-; expected
Ignoring any other potential errors in your code (or due to its presentation to us here), you are attempting to declare another method in main.
public int SearchSortAlgorithm () {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
aSortedArray = quickSort(anArray, 5000);
}
This needs to be moved out of main. And also fixed to actually return an int. And main's signature should be public static void main(String[] args).
Although, it should really be returning an int[] instead...
public static int[] searchSortAlgorithm (final int[] anArray) {
TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
return quickSort(anArray, 5000);
}
...and called in your main method like this...
int[] aSortedArray = searchSortAlgorithm(anArray);
for (int k = 0; k <= 50; k++) { // would be better to use aSortedArray.length
System.out.print(aSortedArray[k] + " ");
}

Converting ArrayList to Array - not sure about how using it [duplicate]

This question already has answers here:
How to convert an ArrayList containing Integers to primitive int array?
(19 answers)
Closed 9 years ago.
This is my second program in Java, and its the first time I'm using an arrayList.
I searched about how to convert it, and used the methods i found, but I get an error...
package eliminarepetidos;
import java.util.ArrayList;
import java.util.Random;
public class Eliminarepetidos {
public static ArrayList<Integer> eliminaRepetidos (int[] vet){
ArrayList<Integer> retorna = new ArrayList<>();
for(int i = 0; i<vet.length; i++){
for (int j = i + 1; j < vet.length; j++)
if ((vet[i] == vet[j])&&(vet[i]!=0)) vet[j]=0;
if(vet[i]!=0) retorna.add(vet[i]); }
return retorna;
}
public static void imprime (int[] vet, int numElem){
System.out.print("Vetor resultante:");
for (int i = 0;i<numElem;i++)
System.out.print(" " +vet[i]);
}
public static void main(String[] args) {
int[] t;
t = new int[10];
Random generator = new Random();
for(int i = 0; i<10; i++)
t[i] = generator.nextInt(12) +9;
ArrayList<Integer> temporario = new ArrayList<>();
temporario = eliminaRepetidos(t);
int [] vetfinal = temporario.toArray(new int[temporario.size()]); //line with error
imprime(vetfinal,vetfinal.length);
}
}
How should I be using the command to make it work properly?
Thanks!
Any ArrayList can be converted to a simple array using toArray(<Type> t) (ArrayList<Thing> list -> Thing[] arr = list.toArray(new Thing[0])), but that's likely not your real question.
Your real question, based on the code you've shown, is far more likely: "how do I iterate over an arraylist?", to which the answer is: "the same as for arrays or any other collection, use the for loop in its foreach pattern":
int[] numbers = {...}
ArrayList<Thing> things = new ArrayList<Thing>();
thing.add(new Thing(...));
...
for(int i: numbers) {
System.out.println(i); // will print each element in the array
}
for(Thing t: things) {
System.out.println(t); // will print each element in the arraylist
}
This use of the for loop has been part of plain Java since v1.5 =)

Categories

Resources