How do I fix this error and what does it mean?
java.lang.ArrayIndexOutOfBoundsException: 5
at Sort.sort(Sort.java:29)
at Sort.<init>(Sort.java:13)
at SortedArray.<init>(SortedArray.java:23)
Here is the code:
import java.util.Scanner;
import java.util.Random;
public class SortedArray
{
Scanner input = new Scanner(System.in);
int [] Array;
Sort sortedArray;
int sizeOfArray;
public SortedArray()
{
System.out.print("Enter the number of values to put in the array: ");
sizeOfArray = input.nextInt();
Array = new int [sizeOfArray];
System.out.println("");
for(int i = 0; i < sizeOfArray; i++)
{
Random r = new Random();
Array[i] = r.nextInt(100) + 1;
System.out.println(Array[i]);
}
sortedArray = new Sort(Array, sizeOfArray);
sortedArray.display();
}
}
public class Sort
{
int[] array;
int sizeOfArray;
public Sort(int[] oldArray, int sizeOfOldArray)
{
sizeOfArray = sizeOfOldArray;
array = new int [sizeOfArray];
for( int i = 0; i < sizeOfArray; i++)
{
array[i] = oldArray[i];
}
sort();
}
public void display()
{
for ( int i = 0; i < sizeOfArray; i++){
System.out.println(array[i]);
}
}
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; i++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
private void swap(int x, int y)
{
int temp;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}
I get the error when I run the program and enter the value. The program is supposed to sort the numbers from greatest to least. I'm not sure what is wrong.
First, what it means: you have an array and are trying to acces an index that is outside its range (below 0 or bigger or equal than the length of the array).
The probable cause is:
for (int j = 0; j < sizeOfArray; i++)
Notice that you check that j does not get too big but you are increasing i.
The Problem is that the inner loop also incrementsi which isn't correct in this situation!
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; j++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
Your problem is on this line
for (int j = 0; j < sizeOfArray; i++)
it should be
for (int j = 0; j < sizeOfArray; j++)
Related
Please click here to see my task's screenshot
Hello, could you please help me? What is wrong with my code? I understand that there is something wrong in my Array's length or my If statement, but i couldnot able to find out it.
Thank you very much!
import java.util.Scanner;
class TripleSwapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the count of your elements: ");
int count = in.nextInt();
System.out.println("Your array before sorting: ");
int A[] = new int [count];
for (int i = 0; i < 10; i++) {
A[i]=in.nextInt();
}
boolean changed =false;
do {
for (int i = 0; i < A.length-1; i++) {
if (!(A[i+1]>A[i]) && !(A[i+1] > A[i+2])) {
int temp;
temp = A[i];
A[i]= A[i+1];
A[i+1] =temp;
}
}
for (int i = 0; i < A.length-1; i++) {
if (A[i] >A[i+1]) {
int temp;
temp = A[i];
A[i]= A[i+1];
A[i+1] =temp;
changed=true;
}
}
}while(changed);
System.out.println("Your array after swapping");
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
}
You are getting ArrayIndexOutOfBoundsException because if you enter to be less than 10 it will throw an exception.
for (int i = 0; i < 10; i++) {
A[i]=in.nextInt();
}
Used instead
for (int i = 0; i < count; i++) {
A[i]=in.nextInt();
}
public static int[] sortByScores(double[] scores){
double temp;
int i,j;
int[] scoreIndex = new int[3];
for (i = 0; i <= scores.length; i++)
for (j = i+1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
scoreIndex[i] = j;
scoreIndex[j] = i;
}
}
return scoreIndex;
}
This method sort the "scores" array in descending order and store which index key is changed from the array in "scoreIndex" array.
This method doesn't work if I enter 1,3,2,4
Is they any better way to store the index key changes log?
Example if 1 enter:
1
2
4
3
Sorted will be:
4
3
2
1
And sortIndex should be:
Key Value
0 3
1 2
2 0
3 1
You can actually get the array containing the proper ordering of the elements at certain indices without sorting this array, for example, by doing this:
for(int i = 0; i < scores.length; i++) {
for(int j = i; j < scores.length; j++) {
if(scores[scoreIndex[j]] > scores[scoreIndex[i]]) {
int temp = scoreIndex[j];
scoreIndex[j] = scoreIndex[i];
scoreIndex[i] = temp;
}
}
}
In short, at the beginning of this method we are creating an array which contains the current order of indices in your scores[] array, this is 0, 1, ..., scores.length-1. Then, we perform an operation similar to standard sorting but not in terms of the scores[] array, but in terms of the scoreIndex[] array.
Once we have this array sorted, we can create another array and and place its elements at the appropriate position by:
double[] copy = new double[scores.length];
for(int k = 0; k < scores.length; k++) {
copy[k] = scores[k];
}
for(int n = 0; n < scores.length; n++) {
scores[n] = copy[scoreIndex[n]];
System.out.println(scores[n]);
}
So, to put it together:
public static int[] sort(double[] scores) {
int[] scoreIndex = new int[scores.length];
for(int i = 0; i < scores.length; i++) {
scoreIndex[i] = i;
}
for(int i = 0; i < scores.length; i++) {
for(int j = i; j < scores.length; j++) {
if(scores[scoreIndex[j]] > scores[scoreIndex[i]]) {
int temp = scoreIndex[j];
scoreIndex[j] = scoreIndex[i];
scoreIndex[i] = temp;
}
}
}
double[] copy = new double[scores.length];
for(int k = 0; k < scores.length; k++) {
copy[k] = scores[k];
}
for(int n = 0; n < scores.length; n++) {
scores[n] = copy[scoreIndex[n]];
System.out.println(scores[n]);
}
return scoreIndex;
}
First, you should declare scoreIndex as:
int[] scoreIndex = new int[scores.length];
And, in every outer loop, you find the max element, set it as scores[i], at the same time, set scoreIndex[indexOfMaxElement] = i. To achieve this, you also need a copy of the origial array.
Here is the complete code:
public class Main {
public static void main(String[] args) {
double[] array = new double[] {1, 2, 4, 3};
int[] result = sortByScores(array);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static int[] sortByScores(double[] scores){
int[] scoreIndex = new int[scores.length];
double[] copy = new double[scores.length];
boolean[] records = new boolean[scores.length];
// copy
for (int i = 0; i < scores.length; i++) {
copy[i] = scores[i];
}
for (int i = 0; i < scores.length; i++) {
// find the max element
for (int j = i + 1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
double temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
}
}
// set the max element's index
for (int k = 0; k < copy.length; k++) {
if (copy[k] == scores[i] && !records[k]) {
scoreIndex[k] = i;
records[k] = true;
break;
}
}
}
return scoreIndex;
}
}
My one worked too but #user6690200 your one is way better.
public static int[] sortByScores(double[] scores){
double temp,temp2;
int i,j;
int[] scoreIndex = new int[3];
double[] scoreBackup = new double[scores.length];
double[] scoreBackup2 = new double[scores.length];
// Generating unique score, beacuse student can have same score
for(i=0;i<scores.length;i++)
scoreBackup[i] = scores[i]*(i+1);
for(i=0;i<scores.length;i++)
scoreBackup2[i] = scores[i]*(i+1);
for (i = 0; i < scores.length; i++) {
for (j = i+1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
temp = scores[i];
temp2 = scoreBackup2[i];
scores[i] = scores[j];
scoreBackup2[i] = scoreBackup2[j];
scores[j] = temp;
scoreBackup2[j] = temp2;
}
}
}
for(i = 0; i<scores.length;i++)
for(j=0;j<scores.length;j++)
if(scoreBackup[i] == scoreBackup2[j])
scoreIndex[i] = j;
return scoreIndex;
}
It only prints out the average to the first column but doesn't do anything for the next.
it only prints out 717, for the first column average. It is a ragged array. Everything else compiles fine.
import java.util.Scanner;
import java.io.*;
public class Fitness
{
public static void main(String [] args)
{
int [][] week = {{800,1000,100},{450,100,845,20,1200,200},{1800,250,400},{0,1500,800,120},{600,500},{700,1400,1700,100},{675}};
System.out.println("Average over 7 days");
avgCalb(week);
static void avgCalb(int [][] x)
{
for(int j = 0; j < x[0].length; j++)
{
int colTotal = 0;
for(int i = 0; i < x.length; i++)
{
colTotal = colTotal + x[i][j];
}
System.out.println(colTotal/7);
break;
}
}
}
summing columns
static void avgCalb(int [][] x)
{
int[] colTotal = new int[x.length];
for(int j = 0; j < x.length; j++)
{
for(int i = 0; i < x[j].length; i++)
{
colTotal[i] += x[j][i]
}
}
for(int i = 0;i<colTotal.length;i++) {
System.out.println((double)colTotal[i]/colTotal.length);
}
}
summing rows
static void avgCalb(int [][] x)
{
for(int j = 0; j < x.length; j++)
{
int colTotal = 0;
for(int i = 0; i < x[j].length; i++)
{
colTotal += x[j][i];
}
System.out.println(colTotal/x[j].length);
}
}
How can I make a program that prompts the size of an array and fill it with random numbers, and then add all the numbers that are not at the edge?
Heres the code:
import javax.swing.*;
public class array {
int matrizNN[][];
public void setMatrizNN(int n){
matrizNN = new int[n][n];
for (int i = 0; i < matrizNN.length; i++) {
for (int j = 0; j < matrizNN[i].length; j++) {
matrizNN[i][j]= (int)(Math.random()*10);
System.out.print(" "+matrizNN[i][j]);
}
System.out.println(" ");
}
}
import javax.swing.*;
public class array {
int matrizNN[][];
public void setMatrizNN(int n){
matrizNN = new int[n][n];
for (int i = 0; i < matrizNN.length; i++) {
for (int j = 0; j < matrizNN[i].length; j++) {
matrizNN[i][j]= (int)(Math.random()*10);
System.out.print(" "+matrizNN[i][j]);
}
System.out.println(" ");
System.out.println("Size "+matrizNN.Length);
}
}
public static void setMatrizNN(int n){
matrizNN = new int[n][n];
for (int i = 0; i < matrizNN.length; i++) {
for (int j = 0; j < matrizNN[i].length; j++) {
matrizNN[i][j]= (int)(Math.random()*10);
System.out.print(" "+matrizNN[i][j]);
}
System.out.println(" ");
}
int sum=0;
System.out.println("=========================");
for (int i = 1; i < matrizNN.length-1; i++) {
for (int j = 1; j < matrizNN[i].length-1; j++) {
//System.out.print(matrizNN[i][j]);
sum+=matrizNN[i][j];
}
}
System.out.println("sum is :"+sum);
}
If you havent find the solution yet here is the code. Hope this is what you want.
You seem to have an idea of how to fill matrizNN[][]. To add the non-edge values up, you can use a similar set of for loops but with the first and last values omitted. Here's the basic idea:
int centerTotal = 0;
for (int i = 1; i < matrizNN.length - 1; i++) {
for (int j = 1; j < matrizNN[i].length - 1; j++) {
centerTotal += matrizNN[i][j];
}
}
System.out.println(centerTotal);
Assume you are given an int variable named nPositive and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the number of all the elements in the entire 2-dimensional array that are greater than zero and assign the value to nPositive.
Code:
for(int i=0; i<a2d.length; i++){
int nPositive;
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive = a2d[i][j];
}
}
}
It has a compilation error. Why?
The iiner cycle is incorrect:
for(int j=0; j<a2d[i].length; j++){
You didn't initialize nPositive.
// make nPositive a global variable
int nPositive = 0;
for(int i=0; i<a2d.length; i++){
for(int j=0; j<a2d[a2d.length-1].length; j++) {
if(a2d[i][j] > 0) {
nPositive += a2d[i][j]; // add the value into nPositive as you go through the array
}
}
}
I tested it and find that,There is no any compilation error in your code...
for(int j=0; j<a2d[a2d.length-1].length; j++){//
let the length is a2d[10][10]
on statement a2d[a2d.length-1].length ,is equal a2d[10-1].length ,is equal a2d[9].length=>10
your algo is working fine for me ,i found no any error
here's my test code
public class A2dTest {
public static void main(String[] arr) {
int[][] a2d = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a2d[i][j] = (int) (Math.random() * 100) + 1000000;// all positives
}
}
for (int i = 0; i < a2d.length; i++) {
int nPositive = 0;
for (int j = 0; j < a2d[a2d.length - 1].length; j++) {
if (a2d[i][j] > 0) {
nPositive = a2d[i][j];
System.out.println("nPositive=" + nPositive);
}}
}
}
}
I believe this is one of the questions on codeLab. You just need to properly initialize nPositive at 0 and increment it for every positive integer. That's all they're looking for involving the output. So your code needs to be:
nPositive = 0;
for (int i = 0; i < a2d.length; i++)
{
for (int j = 0; j < a2d[i].length; j++)
{
if (a2d[i][j] > 0)
{
nPositive++;
}
}
}