Array out of bounds exception:100 [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This program is giving me array out of bounds exception :100
How to resolve??? also tell me whether my printing method of array is correct or not?
import java.util.Random;
import java.lang.Math;
class MersennePrime {
public int[] MersennefindPrime() {
int i=0;
int k=0;
int array[] = new int[100];
for(i=2;i<100;i++)
{
int count=0;
for(int j=2;j<=Math.sqrt(i);j++ )
{
if(i%j==0)
{
}
else
{
array[k]=i;
k++ ;
}
}
}
return array;
}
}
public class MersenneRandomNumbers
{
public static void main(String[] args)
{
MersennePrime mrn = new MersennePrime();
int array[] =mrn.MersennefindPrime();
for(int s=0;s<=array.length;s )
System.out.println("array is " array[s]);
}
}
}

This
for(int s=0;s<=array.length;s )
System.out.println("array is " array[s]);
}
should be like this
for(int s=0; s<array.length; s++) {
System.out.println( "array is " + array[s] );
}
Note the change from <= to <!
In your code, within the last loop s equals array.length, which is just the first index outside the boundaries of the array.
EDIT
Beside the upper syntactic error, there is a logical one here as well. In MersennefindPrime() the outer loop runs from 0 to 100, while the inner loop runs ("worst case") from 2 to 10. So there might be about 10 * 100 times, where you increase k and try to set the respective index in the array. This is far more, than the 100 items you allocated the array for!
If you can't be sure about the extent of your array at initialization, use some class, that implements the interface List. This could then look like this:
public List<Integer> MersennefindPrime() {
ArrayList<Integer> array = new ArrayList<Integer>();
for(int i=2;i<100;i++)
{
for(int j=2;j<=Math.sqrt(i);j++ )
{
if(i%j==0)
{
}
else
{
array.add( i );
}
}
}
return array;
}
You would have to adjust the code in main() accordingly!

Related

Reversing an Array: Please check this code out [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am struggling to understand why the following code cannot reverse an array.
I have made a copy of the array.
As you can see below, I have used a for loop and started the counter from 0 until the array's length. I set the first element of the original array to be equal with the last. And, the second from the beginning of the array to be equal with the second from the end. And, so on.
But the result gives me back the original array, not the reversed one.
I have pasted the whole code here so you can copy it into your IDE. Please help me figure this out.
Thank you very much in advance.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int[] myArray = normal(5);
reverse(myArray);
}
public static int[] normal(int count){
int [] array = new int[count];
for(int i = 0; i < count; i++){
array[i] = input.nextInt();
}
return array;
}
public static void reverse(int[] array){
int[] reverse = Arrays.copyOf(array, array.length);
for(int i = 0; i < array.length; i++){
array[i] = reverse[(array.length - i)-1];
}
System.out.println(Arrays.toString(reverse));
}
}
You are printing reverse-
Replace this line
System.out.println(Arrays.toString(reverse));
with this
System.out.println(Arrays.toString(array));
This line is the culprit
System.out.println(Arrays.toString(reverse));
Replace it with
System.out.println(Arrays.toString(array));
A better way to interpret the result would be to use something similar
public static void main(String[] args) {
int[] myArray = normal(5);
System.out.println("Before reverse");
System.out.println(Arrays.toString(myArray));
reverse(myArray);
System.out.println("After reverse");
System.out.println(Arrays.toString(myArray));
}
and remove the print statements from the recursive loop completely.

readNumberAsArray assignment [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Write a readNumberAsArray method that takes an integer as a parameter and creates a new int array with that number as the length. Subsequently, a corresponding number of int values ​​should be read in with the aid of the IOTools and the array filled with them returned, whereby only single-digit numbers (0-9) should be taken into account as input. If the parameter is negative, the method should return null. For negative or two-digit value entries, the entered value should be replaced by 0. Use a for loop to read in the values. A text output when using the IOTools is not necessary.
My program is not working.
import Prog1Tools.IOTools;
package com.company;
public class Main {
public static void readNumberAsArray(int a) {
int [] a = new int[];
int a = IO.Tools.readInteger () ;
for int (a = 0 ; a<10 ; --a) {
System.out.println('0');
for (int a=0; a>10; a++) {
System.out.println(a);
for (int a=10; a=>10; a++) {
System.out.println('0');
}
}
}
// write your code here
}
}
I think you have to just implement what you're asked. Step by step. There's no special logic.
public int[] readNumberAsArray(int n) {
// negative or two-digit values should be replaced with 0
if (n <= 0 || n > 9)
return new int[0];
// creates a new int array with that number as the length
int[] arr = new int[n];
// corresponding number of int value should be read in with the aid of the IOTools
for (int i = 0; i < arr.length; i++)
arr[i] = IO.Tools.readInteger();
return arr;
}

How to go through the deepest elements in an array of arrays? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
public static void main(String[] args) {
int [][] a={{1,2,3},{4,5,6}} ;
for(int x:a)
System.out.print(" "+x);
}
}
Could someone please tell me how would I print each value in the array?
You have to use for each loop twice. In first loop you iterate over all the array and in the inner loop you iterate over all the integers in the outer array.
int [][] a={{1,2,3},{4,5,6}} ;
for(int []x:a){
for(int y : x){
System.out.println(y);
}
}
As you're having a dual-dimension array, you need two loops:
public static void main(String[] args) {
int [][] a={{1,2,3},{4,5,6}} ;
for(int[] r:a) {
for (int x:r) {
System.out.print(" "+x);
}
}
}

Java beginner- Can somebody debug my code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
import java.util.*;
import javax.swing.*;
public class Practice {
public static void main(String[] args){
int[] numbers = {1, 2, 3, 14, 15, 16, 17};
getSmall(numbers);
}
public static void getSmall(int[] ar){
int small=0;
for(int i=0; i<ar.length; i++){
if(ar[i]<small)
small = ar[i];
}
System.out.println(small);
}
}
The program is to find the smallest number in the array, there is no compiler error but it doesn't show the correct result.
Thank you in advance!
public static void getSmall(int[] ar){
int small=ar[0];
for(int i=1; i<ar.length; i++){
if(ar[i]<small)
small = ar[i];
}
System.out.println(small);
}
Setting small initially to 0 is a bad idea as you are hoping that your array contains an element less than that for the answer to be correct.
A common idiom is to initialise small to ar[0] (having, of course, first checked that ar contains at least 1 element). Then run your loop from 1.
for(int i = 1;
(I dislike initialising small to a very large number since that puts the answer to your function in an undefined state if ar does not have any elements.)
Change
int small = 0
to
int small = ar[0];
Don't init small=0,
change to int small = ar[0]
You can also use
int small=Integer.MAX_VALUE;
in place of
int small=0;
this code will print small value, give the max of integer
Change this
public static void getSmall(int[] ar) {
int small = 0;
for (int i = 0; i < ar.length; i++) {
if (ar[i] < small)
small = ar[i];
}
System.out.println(small);
}
to
public static void getSmall(int[] ar) {
int small = ar[0];
for (int i = 1; i < ar.length; i++) {
if (ar[i] < small)
small = ar[i];
}
System.out.println(small);
}
because variable small is not assigned to any value from your array

Return an array with method in Java [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 have a doubt.
I am developing the following code which will be a multplication table for a number that you manually introduce. What I cannot get is to print the table. I don't know what is going on because as far as I know, all the code is right written.
public class Tabla
{
public static void main (String[] args)
{
int n=4;
Tabla table = new Tabla ();
int dato [];
dato=table.producto(n);
for (int j=1;j<=10;j++)
{System.out.println(dato[j]);}
}
public int [] producto(int num)
{
int a[]={'0'};
for (int i=1;i<=10;i++)
{a[i]=num*i;}
return a;
}
}
Any ideas??
Thanks in advance!
**I changed the code to:
public class Tabla
{
public static void main (String[] args)
{
int n=4;
int j;
Tabla table = new Tabla ();
int dato[]=new int [10];
dato=table.producto(n);
for (j=0;j<10;j++)
{System.out.println(dato[j]);
}
}
public int [] producto(int num)
{
// make a 10-element array
int a[] = new int[10];
// fill up the array with products
for (int i = 0; i < 10; i++)
{a[i] = num * (i+1); }
return a;
}
}
Works like a charm!
Now I am wondering why the compiler threw the "ArrayIndexOutOfBoundsException" when I had the for cycle as for (int i = 1; i <=10; i++)
Thanks for the help! :D
Building off of Wasserman's answer, what you should have written is as follows:
public int[] producto(int num)
{
// make a 10-element array
int a[] = new int[10];
// fill up the array with products
for (int i = 0; i < 10; i++)
a[i] = num * (i + 1);
return a;
}
You created a single-element array, whereas you wanted a 10-element array to fill up.
Two problems:
int a[]={'0'};
This line creates an array a with only one element -- not the 11 you're trying to fill -- and moreover, that one element is the ASCII code for the character 0, which is almost certainly not what you want.

Categories

Resources