Trying to display the two dimmensional array contents in java - java

I'm a new to java.I'm looking to print the contents in the two dimmensional array namely myPoints.However,when i'm printing the code.it is throwing up the following error.
mypoints4
i value is 0
2
i value is 1
5
i value is 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
2 at perceptron.main(perceptron.java:37)
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import java.awt.*;
class perceptron{
public static void main(String[] args){
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
int [][] myplot = {{3,4},{5,6},{5,5},{5,3}};
int sum=0;
int i=0;
System.out.println("mypoints"+myPoints.length);
while(i<=myPoints.length){
System.out.println("i value is"+i);
System.out.println(myPoints[i][i]);
i = i+1;
}
}
}

You need to use nested loops for that.
The reason you get the ArrayIndexOutOfBoundsException is because you're using myPoints[i][i], so when i is 2 it is looking for the third element of the third inner array (ie {7,8}) when it doesn't exist

This is because of while(i<=myPoints.length) need to be while(i<myPoints.length).. In case of array in size 5, your i should be i=0, i=1, i=2, i=3, i=4.. Exclude 5.
Another issue is:
System.out.println(myPoints[i][i]);
should be : System.out.println(myPoints[i][0] + " " + myPoints[i][1]);
Because the second dimensional of youre array is only 2 size.. and not 5

Your condition on the while loop must be "less" not "less or equal".
This is because the array index is zero based and hence the index range is always from 0 to (length - 1).

You're going up to (and including) the length of the outer array. This is an array index out of bounds because the indices of an array of length n are 0 ... (n-1). So trying to access index n is out of bounds.
You're accessing the sub array at index i, which is out of bounds for later sub arrays. This would work for a square matrix (you'd read down the diagonal), but your matrix is 4*2, so myPoints[2][2] is OOB, because you can't access index 2 of the length 2 array {7,8}.
The simplest way to iterate over every element in a 2-D array is to have to have a nested loop, like such:
for(int i = 0; i < myPoints.length; i++){
for(int j = 0; j < myPoints[i].length; j++){
System.out.println(myPoints[i][j]);
}
}
An even more concise way of doing this is by using a for-each loop, which gets rid of indices entirely and just gives you each element in the array, in order:
for(int[] row : myPoints){
for(int val : row){
System.out.println(val);
}
}
An even more concise way is to use the method Arrays.deepToString(...):
System.out.println(Arrays.deepToString(myPoints));

Related

How to initialise an int java array of size n initially empty?

In a function,I want to initialise a java array of max size n, which is empty initially.If I add 3 elements(say n>3) and return the array, the array should contain only the 3 elements and not 3 elements followed by (n-3) 0's.
//PSEUDO CODE
func(){
//Create array A of max size 5
A[0]=1;
A[1]=2;
A[2]=3;
return A;
}
main(){
int[] B=func();
//B.length should give 3
for (int i=0;i<B.length;i++){
print B[i];
}
/*Should print 1 2 3
and Not 1 2 3 0 0
*/
}
And I don't want to use array list.I want to use java array only.
Your problem seems to be that you only want to print the non-default values of the array. If your values are always different from zero, then you can just do:
for (int i=0;i<B.length;i++){
if (B[i] != 0){
print(B[i]);
}
}
However, if your values can also be zero, you can also keep a counter of how many values you currently have, and only print that many values:
int counter = 3; //the array might be {1, 2, 3, 0, 0}
for (int i=0; i<counter; i++){
print(B[i]); //will print "1 2 3"
}
The counter must be incremented everytime you add a value.
Both solutions are limited though, depending on how you access and use the array.
then u have to make the array dynamic by urself. Everytime u add an element to the array create a new array of size=no of elements (let u r adding the 3rd element then size of new array would be 3). take the elements from old array to the new one. Each time u add 1 element u have to follow this.

Why the output is 0 for a[0] instead of -1?

I am new to java array, I would like to calculate small element in an array when array contains negative elements.
class test_array {
//test_array class
public static void main(String args[]) {
int[] a = {4, 2, 99, 9, -1, 0};
int small = a[0];
for (int i = 1; i < a.length; i++) {
if(a[i]<small) {
a[0]=a[i];
a[i]=small;
}
}
System.out.println(a[0]);
}
}
int small = a[0];
here you gave 4 to small
you didn't change this value if you find a smaller one. Instead of that you are changing smaller one into this value by
a[i] = small;
this code and small value doesn't change at all. Your 'small' value is always 4.
when it compares a[5] and small (it means 0 and 4) it passes if statement and makes a[0]=a[5] ( gives it '0').
You are comparing only with first char of array with this algoryhtm but you need to compare it with a dynamic "small" value. Change code like that.
class test_array {
//test_array class
public static void main(String args[])
{
int[] a={4,2,99,9,-1,0};
int small=a[0];
for (int i=1;i<a.length;i++)
{
if(a[i]<small)
{
small=a[i];
}
}
System.out.println(small);
}
}
Choose first array element as small, then compare. If there is any smaller value, give this value to 'small'. Do it in a loop for all array and find smallest value.
Bonus: Btw it's good to work on simple algorythms like that for starting but know that for hard times there is easier way to sort arrays and find min and max values like
Arrays.sort(arr);
It will sort all array. Then arr[0] will be min and arr[arr.lenght-1] will be max values.
Though there are various ways to find the smallest element from an array but lets focus on your method. Your method brings the smallest element at the 0th index. You do not need the variable small, Also you need to modify the code inside the if condition as below.
if(a[i]<a[0]){
int temp = a[i];
a[i] = a[0];
a[0] = temp;
}
Above will shift the smallest element at the 0th index. Other way simply keep assigning the smaller element as you get while iterating the array in a variable and after the loop execution completes, you can use the smallest element. This alternate approach is more efficient if you just want to know the smallest element, as it does not involve shifting of elements. This approach is mentioned by #ReadyFreddy
https://stackoverflow.com/a/42082585/504133
You are confused whether you want to keep the smallest element in the variable "small" or in the 0th element of the array. You are changing a[0] but comparing to small.
Your code is printing the last element which is compared.
Iteration 1
i =1
a[1]=2
small =4
a[1]<small -> a[0] =2 a[1] -> 4
Iteration 2
i =2
a[2]=99
small =4
a[2]<small // False
Iteration 3
i =3
a[3]=9
small =4
a[3]<small // False
Iteration 4
i =4
a[4]=-1
small =4
a[4]<small -> a[0] =-1 a[4] -> 4
Iteration 5
i =5
a[5]=0
small =4
a[5]<small -> a[0] =0 a[5] -> 4
In the last iteration a[0] will become 0 and when you print it outside the loop it displays 0.
If you are looking to find the smallest element in the array please refer Find the smallest element in an array.
Hope this helps.
I just tried something different hope this is much simpler to compare and find the least element in the array.
public static void main(String args[]) {
int[] a = { 4, 2, 99, 1, -2, 0 };
Arrays.sort(a);
System.out.println(a[0]);
}

Error finding largest randomly generated double in ArrayList Java

I'm trying to get a program to work where I generate 1,000,000 random numbers between 0 and 1 and then find and print the largest number.
I've got the generator to work and managed to insert each double generated into an ArrayList but I cannot seem to figure out how to find the largest number in the list. At the moment the current code throws the error "java.lang.IndexOutOfBoundsException".
This is all probably due to me being new to the ArrayList and not being fluent with its commands and how it works but I would really appreciate some help on what I'm doing wrong here as I've been stuck for a while.
import java.util.ArrayList;
import java.util.Random;
public class milran {
public static void main(String[] args) {
Random r = new Random();
ArrayList<Double> myList = new ArrayList<Double>();
for (int i = 1; i<=1000000; i++){
double randomValue = 0.0+(1.0-0.0)*r.nextDouble();
myList.add(randomValue);
}
double max = myList.get(1);
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
if (test>max){
max = test;
}
}
System.out.println(max);
}
}
First of all take a look at the docs for java.util.Collections and java.util.ArrayList.
Secondly, the ArrayIndexOutOfBoundsException is being triggered by this...
for (int z=2; z<=myList.size(); z++){
double test = myList.get(z);
...
}
This is because array indexing starts at 0, therefore the last element is myList.size() - 1. In other words, when z = myList.size(), it is out of bounds.
Also, in your first for loop, you are using i = 1; 1 <= 1000000. It makes much more sense to use i = 0; i < 1000000 as you can use i to touch each element in an array (or list).
for( i = 0; i < 1000000; i++ )
{
// do something with myArray[i]
}
Here's what I would do after the values have been inserted...
Sort the array: Collections.sort(myList);
Retrieve the last element: System.out.println( myList.get( myList.size() - 1 ) );
...and that's it.
If you need to implement the actual sort yourself then i'd consider using a primitive double array (double[]) rather than a Collection.
Otherwise, if you are using a collection, you can use a foreach loop.
for( Double d : myList ) // for each Double 'd' in myList
{
// do something with d
}
N.B. Another potential issue with this line in the second loop
double test = myList.get(z);
This automatic conversion from Double (object) to double (primitive) is called unboxing. There will be a performance cost, especially when repeated a million times. In the first loop you are converting the other way (autoboxing) – also a million times.
ArrayList start count its elements from 0. You need to replace myList.get(1) to myList.get(0), int z=2 to int z=1 and z<=myList.size() to z<myList.size().
This line: for (int z=2; z<=myList.size(); z++) { is wrong. It should be for (int z=1; z<myList.size(); z++) {.
This is because arrays and lists are 0 based, so a list of size 2 has 2 elements - index 0 and index 1. Currently you try to index into the element number equal to the size, which does not exist.
Along the same line, myList.get(1); should be myList.get(0);.
This is unrelated to your problem, but this line 0.0+(1.0-0.0)*r.nextDouble(); can be much more easily written as r.nextDouble();. I'm not sure what you were trying to do by doing 0 + 1 - 0.
As others have already pointed out, you have an error in your for-loop condition that causes the index to go out-of-bounds.
One way that you can avoid this in the future is by using Java's for-each loop syntax instead of trying to manage the index yourself.
for (Double test : myList) {
if (test>max){
max = test;
}
}
This syntax makes your intent much clearer than the traditional indexed for syntax and removes a point of potential error (managing the index and the bounds of the list) from your hands.

Why is my int[] array loop out of bounds?

Warning: I am very new to Java and programming in general. I'll try to be as clear as possible.
I am attempting to take a simple integer (inputnumber), convert it to a string (temp), create a new int[] array (numberarray), and loop through this int[] array, starting from the last digit, and print out the name of the digit.
I am rather sure that the conversion from integer to String to int[] array was functional due to Eclipse debugging, but am stumped as to why I am getting an ArrayOutOfBounds message from Eclipse for such a simple for loop. Any clues as to what I am doing wrong is appreciated.
String temp = inputnumber.toString();
int[] numberarray = new int[temp.length()];
for (int i=0;i<temp.length();i++) {
numberarray[i] = temp.charAt(i);
}
for (int i=temp.length();i>0;i--) {
if (numberarray[i]==1) System.out.print("one.");
if (numberarray[i]==2) System.out.print("two.");
if (numberarray[i]==3) System.out.print("three.");
if (numberarray[i]==4) System.out.print("four.");
if (numberarray[i]==5) System.out.print("five.");
if (numberarray[i]==6) System.out.print("six.");
if (numberarray[i]==7) System.out.print("seven.");
if (numberarray[i]==8) System.out.print("eight.");
if (numberarray[i]==9) System.out.print("nine.");
if (numberarray[i]==0) System.out.print("zero");
}
The Eclipse error message I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at jt.Intermediate8.main(Intermediate8.java:44)
Arrays are 0-indexed in Java. This means the last value is at index NUMBER_OF_ELEMENTS - 1
Therefore, in your for loop, you should change
int i=temp.length() // this is last index + 1 (since we are starting from 0)
To:
int i=temp.length() - 1 // this is last index
Also, as #brso05 said, don't forget to change your loop-ending condition to i>=0 since the last value going backwards will be at index 0.
Your for loop:
for (int i = temp.length(); i >= 0; i--)
You're starting the loop at temp.length(). That's not a valid index. Perhaps you want temp.length()-1?
You should be doing temp.length() - 1. The reason is that the array starts with index 0 not 1 so the last element in an array is stored at the length - 1. If there are 10 elements then 0-9 are your indexes. Also change i>0 to i>=0 if you want to hit all elements.
for (int i=(temp.length() - 1);i>=0;i--) {

I get ArrayIndexOutofBoundsException - reverse the array

I get the output for the program mentioned below. In addition Ii also encounter an exception as:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ReverseOrder.main(ReverseOrder.java:15)
Why does this happen?
public class ReverseOrder {
public static void main(String[] args)
{
int anArray[]={1,2,3,4,5,6};
int anotherArray[]=new int[6];
for(int i=5,j=0;i>=0;i--,j++)
{
anotherArray[j]=anArray[i];
}
//System.out.println(anotherArray.length);
//System.out.println(anotherArray[2]);
for(int j=0;j<=anotherArray.length;j++)
{
System.out.println(anotherArray[j]);
}
}
}
Change
for(int j=0;j<=anotherArray.length;j++)
to
for(int j=0;j<anotherArray.length;j++)
Since if it's <= you'll be going out of bounds.
In Java (and most languages), arrays are zero-based. If you have an array of size N then its indexes will be from 0 to N - 1 (total size of N).
The problem is here:
for(int j=0;j<=anotherArray.length;j++)
{
System.out.println(anotherArray[j]);
}
you are accessing a position out of the array. This happen because method length gives you the number of elements in the array, and since the first position of an array is 0 and not 1 you should end the loop on anotherArray.length - 1 and not anotherArray.length.
There are two possible solutions to this where you modify your loop to:
a) for(int j=0;j<=anotherArray.length - 1;j++)or
b)for(int j=0;j<anotherArray.length;j++)
The latter (b) is preferable, since it has less arithmetic operations on it.
change
<=anotherArray.length
to
< anotherArray.length
For example, if array is
int arr[] = new int[2];
arr.length; // it will be 2, which is [0] and [1] so you can't go upto <=length,
// that way you will access [2] which is invalid and so the exception
for(int j=0;j<anotherArray.length;j++)
instead of
for(int j=0;j<=anotherArray.length;j++)
Because arrays are zero-based in Java.
You will get ArrayIndexOutOfBoundsException when you try access the element that's out of Array limit.
for(int j=0;j<anotherArray.length;j++) {
System.out.println(anotherArray[j]);
}
Why do you use this way to reverse your array in first place. Any way
for(int j=0;j<=anotherArray.length;j++) should change to
for(int j=0;j<anotherArray.length;j++)
Consider this too, It is easy.
int anArray[]={1,2,3,4,5,6};
int temp=0;
for (int i=0;i<anArray.length/2;i++){
temp=anArray[i];
anArray[i]=anArray[anArray.length-(1+i)];
anArray[anArray.length-(1+i)]=temp;
}
Now your array is reversed.

Categories