Method for moving an element in an array - java

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.

Related

2D array row and column length

I'm studying 2D array right now, there is a part of 2D array I don't really understand. I will show my code and explain what part I don't understand.
My code:
public static void main(String[] args){
int[][]array={{1,2,3},{1,2,3},{1,2,3}};
}
public static printArray(int[][]a){
for(int row=0;row<a.length;row++){
for(int column=0;column<a[row].length;column++)
}
My question is for the second method of printArray. In the second for loop,what does column<a[row].lengthmeans?
This line gives the size of each row.
You know that
a[0]={1, 2, 3}
a[1]={1, 2, 3}
a[2]={1, 2, 3}
So, a[0].length = a[1].length = a[2].length = 3. Use of this is to ensure that we dont go Out Of Array Bounds.
Java doesn't have 2D arrays. Java has arrays of arrays. The second loop uses column < a[row].length to make sure that you don't iterate past the length of the row-th array. You need this to handle nested arrays of varying length.
That is the condition to check when the limit of each row is reached, in order to avoid an ArrayIndexOutOfBoundsException
A 2D array means that each element of the array is itself an array. The second loop allows you to loop through each {1,2,3} array (in your case). But to do that, you need the length of each array. That's what a[row].length provides.

How to declare string array[] of unknown size (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]

ArrayList for loop only removing only even indexes

I expected this to print [] but it prints [1, 3, 5, 7, 9]. Can anyone explain why every index is not removed?
Thanks.
import java.util.ArrayList;
import java.util.List;
public class test {
public static void main (String args[])
{
ArrayList<Integer> aL= new ArrayList<>();
int[] aList = {0,1,2,3,4,5,6,7,8,9,10};
for(int i: aList){
aL.add(i);}
mystery(aL);
System.out.println(aL);
}
public static void mystery(List<Integer> nums)
{
for (int k = 0; k < nums.size(); k++)
{
nums.remove(k);
}
}
}
If you want to remove all the elements from your array, you have to start at the end and work backwards, otherwise your indices will get messed up.
Consider your array is as follows: {0, 1, 2, 3}
Now you want to loop through and delete starting with the 0th index. So the first loop happens, and now your array looks like this: {1, 2, 3}.
Next time, you loop through, you are deleting the 1st index, but this fails to take into account that the array shifted left, so now your array is: {1, 3}.
I think you can see the problem. So either you continue to delete at index 0: nums.remove(0) or you can start at the end of the array and work back.
Every time you remove an element the list shifts left to fill that element from the higher indices, so when you then increment k you're skipping the element after the one you just removed. You can remove from index 0 until the list is empty.
I usually build my for loops backwards to avoid this problem. It's especially helpful in situations where you want to delete a number of items sporadically from within a list without having to worry about reindexing causing you to remove the wrong items. You can try this:
for(int k = nums.size()-1; k >= 0; k--) nums.remove(k);

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.

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