How to declare string array[] of unknown size (JAVA) - java

I want my String[] array; to be static but I still don't know it's size.
Is there any way to declare string array of unknown size?
As much as possible I don't want to use ArrayList

You don't need to know the array size when you declare it
String[] myArray;
but you do need to know the size when you initialize it (because Java Virtual Machine needs to reserve a continuous chunk of memory for an array upfront):
myArray = new String[256];
If you don't know what the size will need to be in the moment you initialize it, you need a List<String>, or you'll be forced to make your own implementation of it (which is almost certainly worse option).

No, it needs to be declared, and thus have a length before you can set elements in it.
If you want to resize an array, you'll have to do something like: Expanding an Array?

String [] array = new String[1];
it will be garbage collected later after you init with a real array n elements.
array = new String[n];
ofcourse it has a performance decrease but it should be non-importance unless you repeat same for many different arrays.

The list is better for manipulation of an "array" for which you don't know length.

Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List unindexedVectors = new ArrayList();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);

My apologies to the nay-say-ers, this can be done easily.
import java.util.Random;
public class Roll_2 {
static Random random = new Random();
public static void main(String[] args) {
int[] variableArray1 = init(random.nextInt(9)); // random size
int[] variableArray2 = init(random.nextInt(9)); // random size
int[] variableArray3 = init(random.nextInt(9)); // random size
randomaize(variableArray1); // randomize elements
randomaize(variableArray2); // randomize elements
randomaize(variableArray3); // randomize elements
print(variableArray1); // print final
print(variableArray2); // print final
print(variableArray3); // print final
}
private static int[] init(int x) {
int[] arr = new int[x];
return arr;
}
private static void print(int[] body) {
System.out.print("[");
for (int i=0;i<body.length;i++) {
System.out.print(body[i]);
if (i<body.length-1) System.out.print(" ");
}
System.out.println("]");
}
private static void randomaize(int[] body) {
for (int i=0;i<body.length;i++) {
body[i] = random.nextInt(9);
}
}
}
Sample Run 1:
[1 7 2]
[5 2 8 6 8 3 0 8]
[]
Sample Run 2: [2 5 6 8 0 7 0 6] [0 0 1] [2 1 2 1 6]
Sample Run 3: [8 3 3] [7] [1 3 7 3 1 2]

Related

How do you randomly take an element from an array and insert it to another for later use in Java?

For example int new [] {1, 2, 3, 4, 5, 6, 7, 8}, I'd like to take 4 of them randomly then insert them to another array for later use.
Dumb question, but does this also need generators? The elements are already there so I don't see any use for generators here...
Below snippet should do the trick:
private static final Random RANDOM = new Random();
public int[] getRandom4( int[] input ){
final int[] output = new int[4];
for( int i = 0; i < 4; i++ ){
output[i] = input[RANDOM.nextInt(input.length)];
}
return output;
}
Note: I prefer the Random instance to be static, but if you dislike that. Then just move it inside the method
You can but the elements inside ArrayList instead of simple array
and then shuffle the elements usingCollections.shuffle(list)
and then take first three or four elements or whatever you wants.

Method for moving an element in an array

I'm trying to create a simple method to move the first element in an array to the back of the array.
Here's my code
public class Ex5_ShiftLeft {
public static void main(String[] args) {
int[] a = new int[] {6, 2, 5, 3};
swap (a);
}
public static void swap(int[] array){
array[0] = array[array.length];
System.out.println(Arrays.toString(array));
}
}
Eclipse doesn't seem to detect an error with my code, but when I run it, I get the error text
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
4 at
apollo.exercises.ch04_loops.Ex5_ShiftLeft.swap(Ex5_ShiftLeft.java:19)
at
apollo.exercises.ch04_loops.Ex5_ShiftLeft.main(Ex5_ShiftLeft.java:1)"
Any tips?
Arrays represent a segment of memory which your program has reserved to store a series of numbers or whatever else your array has. Because of this, arrays cannot be resized; you can't go past the end of the segment of memory you've reserved because another program might be using that memory. Your solution does not work because it tries to take the first element and put it after the end of the array, which is out of bounds. Instead, you have to remember the first element, then move each element except for the first one space to the left to create room at the end of the array, and then you can put the first element at the end of the array.
I take it as you're a beginner so i'll say just keep at it and you'll sure improve. I improved your code below for you:
public class Ex5_ShiftLeft {
public static void main(String[] args) {
int[] a = {6, 2, 5, 3};
swap (a);
}
public static void swap(int[] array){
int temp = array[0]
array[0] = array[array.length-1];
array[array.length-1]
for(int x : array){
System.out.println(x+" ");
}
}
}
CHANGES:
You can declare an array just with this: int[] myArray = {6,2,5,3};
There was a problem with your swap function. You have to create temporary variable so you can swap the first element of the array with the last.Also, the last element of the array is array[array.length-1]
Second, I used an Enhanced For-loop to print out the array. Hope this helps
The size of an array is basically static.
For this purposes, you can use an ArrayList which is dynamic.
The error is because of line :
array[0] = array[array.length];
If you want to access the last element of the array and populate it to array[0] then use below
array[0] = array[array.length-1];
Use array[0] = array[array.length - 1]; to access the last item in the Array.

Why am I getting ArrayIndexOutOfBoundsException?

So I got this assignment while my teacher is away, and basically I have to make a student project. The student has a name, marks, and average. To calculate the average I decided to store the marks inside a int[] array.
public void addQuiz(int m)
{
int l = (marks.length);
marks[l] = m;
}
int[] marks = new int[8];
But when I run the function:
student.addQuiz(90);
I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
Any help?
I'm not sure what the int[8] part does but it was in the tutorial I followed and it would give me a null pointer without it. There are eight marks in total so I just made it 8.
You can't dynamically add things to an array. You should use an array list instead.
Arraylist<Integer> marks = new ArrayList<Integer>();
then in your addQuiz method:
public void addQuiz(int m) {
marks.add(m)
}
You'll probably also need to change your method for calculating the average a bit, but that should be trivial and I'll leave it to you.
The error says: ArrayIndexOutOfBoundsException: 8
You have an array with 8 elements, indexed from 0 to 7 (inclusive). This array has a length of 8, and you are actually trying to access marks[8], when you only can go up to 7.
In Java, Array index starts from '0'. so, you cannot access the index of the array equal to the length of the array.if your arrays length is '8', then the last index of the array is '7' not '8'. if you are trying to access the illegal index of the array, then ArrayIndexOutOfBoundException is thrown. the code should be changed to
public void addQuiz(int m)
{
int l = (marks.length); //assuming marks is an array of length '8'
marks[l-1] = m; //index is 7 now
}
To calculate the average, you need to sum up the contents of the array (provided all the values are of int values) and then divided by the lenght of the array
int sum = 0;
int avg = 0;
for(int i=0; i<array.length;i++){
sum =sum+array[i];
}
avg = sum/array.length;
Hope this gives an idea
Use Arraylist<Integer> and then you can add to the list dynamically
There is not index in this array for this marks[l] = m;. use marks[l-1] = m;
You can call this for loop in main for getting marks 8 times.
for(int i=0;i<8;i++)
student.addQuiz(<marks you want to enter>, i);
You can define addQuiz function like below
public void addQuiz(int m, int arrayIndex)
{
marks[arrayIndex] = m;
}
int[] marks = new int[8]; //this will be as it is
These are minimal changes. You can make your code better by passing array marks to addQuiz as a parameter. But this will also work, its just that this is not the best way to write code.

How do you get the length value from an array greater than 1D in java?

In java, what would myArray.length be referencing in a 2D array? E.g.
double[][] myArray = new double[3][5];
say you want to run a couple of for-loops over the array without putting the rows and columns in an argument to get hold of their value, is there a neat way to do this?
Use myArray.length and myArray[0].length. (This assumes that all of your "sub"-arrays are the same length.)
In java, what would myArray.length be referencing in a 2D array?
A 2 dimensional array of double is a 1-dimensional array or 1 dimensional array of double. myArray[0] is a an array of double (double[]), as is myArray[1]
So myArray.length is the number of arrays.
say you want to run a couple of for-loops over the array without putting the rows and columns in an argument to get hold of their value, is there a neat way to do this?
You mean you want to access myArray[2][3] without using 3 and 4? There isn't a way to do this in Java
As of Java 5 you can use a different looping construct, "for each", where you avoid using array indices;
class Test {
public static void main( String[] args ) {
int[][] myArray = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } };
for ( int[] outer : myArray ) {
for ( int inner : outer ) {
System.out.println( inner );
}
}
}
}
This prints;
$ java Test
1
2
3
4
5
6

java randomize indices in an array

I have looked at Randomize or shuffle an array Randomize or shuffle an array
I am not sure if this is the best approach to make.
I want to randomize the indices of an array with 3 items.
12
4
5
int numbers[] = new int[3];
I tried using the Maths.Random
int randomoption2 = opmin + (int)(Math.random() * ((opmax - opmin) + 1));
but I then have an issue with repetition of the indices values. What is the best approach to randomize the indices so there is no repetition .
eg
a[1] = 2;
I don't want two elements in the array coming back with an indices of one
http://www.exampledepot.com/egs/java.util/coll_Shuffle.html
public class randomorder {
public static void main(String [] args)
{
randomorder();
System.out.println(randomorder());
}
public static ArrayList randomorder(){
ArrayList nums = new ArrayList();
nums.add(1);
nums.add(2);
nums.add(3);
Collections.shuffle(nums);
return nums;
}
}
I now need to store each of the numbers in variables so they can be outputted
System.out.println(options[0]);
Use Collections.shuffle:
Integer[] numbers = { 1, 2, 3, 4, 5 };
Collections.shuffle(Arrays.asList(numbers));
See it working online: ideone
It uses the Fisher-Yates shuffle internally. This is an efficient shuffling algorithm that won't give you duplicates.
Related
Java's Collections.shuffle is doing what?
How to convert int[] to Integer[] in Java?
Arrays.asList() not working as it should?
Just keep three booleans through an array of booleans. Once you hit 0, 1, or 2 index set them to true.
Choose a random position and do while(boolean[number chosen] == true) redo your random choice.

Categories