So I have been working on this problem for a while now. I keep getting an ArrayIndexOutOfBoundsException but I am unable to locate where the issue lies. If someone could point me in the right direction, I would really appreciate it! Thanks!
public class Answer {
public static void main(String[] args){
double[] y = {23, 11.1, 50.4};
double[] x = {22.2, 46, 100.0};
Answer answer = new Answer();
answer.answer(y, x);
}
public static int answer(double[] y, double[] x) {
int result = 0;
double percent_1, percent_2;
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
// Calculate percent of first 2 x value array items with y
// all y values. Store the results in a seperate list.
for(int i = 0; i < x.length; i++){
percent_1 = compare(y[i], x[0]);
percent_2 = compare(y[i], x[1]);
compareList_1[i] = percent_1;
compareList_2[i] = percent_2;
}
// Compare those lists to find common number
// There you have your answer.
result = (int)compareLists(compareList_1, compareList_2);
return result;
}
// Calculates percentage from x and y values
public static double compare(double y, double x){
double result = 1 - (y/x);
return result;
}
// Finds common value in lists
public static double compareLists(double[] list_1, double[] list_2){
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
if(list_1[i] == list_2[j]){
return list_1[i];
}
}
}
// Just cus this shouldn't ever return.
return 100;
}
}
In your iteration (compareLists), you should use 'length' (not length + 1)
for(int i = 0; i < list_1.length; i++)
for(int j = 0; j < list_2.length; i++)
I think the problerm is in
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
i < list_1.length + 1 or j < list_2.length + 1 change it to
for(int i = 0; i < list_1.length; i++){
for(int j = 0; j < list_2.length ; j++){
remove +1 from each condition.For j < list_2.length + 1 the list_2.length will give you length of array ie lastIndex +1 and you are adding another +1 in it causing loop condition to be j<lastIndex +1 giving you index error on the last iteration of loop in the line if(list_1[i] == list_2[j]){ for list_2[j]
Also in answer method you declare array by
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
and in the loop you are iterating upto x.length if x.length is greater than y.length the you can get the Index error in compareList_2[i] = percent_2;(inside the loop) because its length is y.length.
Related
I searched some entries, but could not answer my question correctly myself.
I'm trying to fill a 2-dimensional array with values.
As a test I'm currently doing this by trying to fill the array with the int number 1.
I do not understand my mistake.
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
Use index 0 to length-1 (as array index start with 0)
public static void creatBoard () {
final int L = 6;
final int H = 6;
// Modell:
int [] [] board = new int [L] [H];
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
}
just debug it and you can see, that
for (int i = 0; i<=board.length; i++) {
for (int j = 0; j<=board.length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
i, and j change values from 0 to 6, it means that it get's out of arrays bounds ( you iterate over 7 lements, instead of 6 ), just remove = sign in loop bodies
for (int i = 0; i<board.length; i++) {
for (int j = 0; j<board[i].length; j++) {
board [i] [j] = 1;
}
System.out.println("");
}
Your board array is of size 6x6 hence the board.length is 6.
When you run the loop for (int j = 0; j<=board.length; ij+) it will run from 0 up to 6 but the array indexing is from 0 to 5. So when j=6, ExceptionOutOfBounds occurs since it will be referring to index board[0][6].
Change the condition in both the loops from <=board.length to <board.length
I have an ArrayList and I want to create a method that will turn it into a 2d array, int[][].
This new 2d array will represent a matrix and it has to be square, so for example if I use [8, 2, 3, 0] the ressult will be {8,2}
{3,0}
public static int[][] convertIntegers(ArrayList<Integer> integers){
int m = (int) Math.sqrt(integers.size());
int[][] ret = new int[m][m];
int cont = 0;
for(int i=0; i<m+1 ; i++)
{
for(int j=0; j<m; j++)
{
cont = cont + 1;
ret[i][j] = integers.get(cont);
;
}
}
return ret;}
Your implementation is almost ok, except for some off-by-one errors:
You need to increment cont after the integers.get call, not before. If you increment before, then the first element of the list will be skipped. An easy way to fix that is to move the incrementing inside the inner loop, counting it together with j.
The outer loop should go until i < m instead of i < m + 1
With the errors fixed:
for (int i = 0, cont = 0; i < m; i++) {
for (int j = 0; j < m; j++, cont++) {
ret[i][j] = integers.get(cont);
}
}
Btw, another way is without using cont at all,
calculating the correct position using i, j and m:
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = integers.get(i * m + j);
}
}
I have an array called blockHeights, which contains 3 values inside of it, namely 1,2,3. So blockHeights[0] is equal to 1.
I also have a loop:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights where it is
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1] and blockHeights[2] together, ignoring blockHeights[0].
How would I go about doing this?
Try the following (I'm assuming the third iteration should only include blockHeights[2], following the pattern):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}
Well, if you want the sum of your array, and the sum of the array without first value
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
this way you only loop once
Try following code:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}
int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
This will print:
6
5
You dont need two for to achieve that.
you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++), and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j], and for i<j, you can just continue the for loop.
as answered by btrs20
This is what I want to do when A is a square matrix.
P - is power.
A & B are square matrices.
User will be asked to enter size of matrix A, and elements of matrix A and to what power they want to raise the matrix to.
Once they input what power, and what elements my program is supposed to calculate this:
(Assuming P = 5)
A^5 + A^4 + A^3 + A^2 + A
I have written a method that adds matrices a method that multiplies them, and a method that raises them to the power and they all work correctly.
The problem I am having is the final step which I showed above A^5 + A^4 + A^ 3...
This is where the problem gets even weirder, my program works when the elements in the matrix are all the same... such that a
2 2 2
2 2 2
2 2 2
matrix will give me the CORRECT output, BUT
1 2 3
4 5 6
7 8 9
matrix will give me the WRONG output and I have no idea why.
This is the method in which the problem is occuring
public static void addPowers(int [][] a, int[][] b, int p) {
while( p != 1){
b = addMatrices(powerMatrix(a,p), b) ;
addPowers(a,b,p-1) ;
return ;
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++)
System.out.print(b[i][j] + "\t") ;
System.out.println();
}
}
Just in case you ask, reason I have the recursive under a while loop is so it won't print over and over and over again.
Thanks for your time! :)
Edit: More clarifying information.
addMatrices is a method that adds matrices with an two int[][] arguments.
powerMatrix is a method that finds the power of a matrix with (int[][], int) arguments.
EDIT Methods being called...
public static int[][] multiplyMatrices(int matrixA[][], int matrixB[][]) {
int temp[][] = new int[matrixA.length][matrixB.length];
int matrix[][] = new int[matrixA.length][matrixB.length];
int sum = 0 ;
for (int i = 0; i < matrixA.length; i++)
{
for (int j = 0; j < matrixB.length; j++)
{
for (int l = 0; l < matrixA.length; l++)
{
sum += matrixA[i][l] * matrixB[l][j] ;
}
temp[i][j] = sum ;
sum = 0 ;
}
}
matrix = temp;
return matrix ;
}
public static int[][] addMatrices(int matrixA[][], int matrixB[][]) {
int temp[][] = new int[matrixA.length][matrixB.length];
int sum = 0 ;
for (int i = 0; i < matrixA.length; i++)
{
for (int j = 0; j < matrixB.length; j++) {
{
sum = matrixA[i][j] + matrixB[i][j] ;
}
temp[i][j] = sum ;
}
}
return temp ;
}
public static int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; n++)
result = multiplyMatrices(result, a);
return result;
}
In your addMatrices method, you should remove the third loop.
Like this:
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {
temp[i][j] = matrixA[i][j] + matrixB[i][j] ;
}
}
I'm trying to convert an integer into an array of digits, then print those digits out in order. It's an early problem in Java: How to Program, and I'm confused as to why I can't make it work.
Here's my class:
public class AnyDigits {
private int[] ns;
public AnyDigits(int n){
this.ns = new int[String.valueOf(n).length()];
for(int i = 0, x = n; x > 0; i++, x = x / 10){
this.ns[i] = x % 10;
}
}
public void printDigits(){
for(int i = this.ns.length - 1; i == 0; i--){
System.out.printf("%d ", this.ns[i]);
}
}
}
I have this code in my main method:
AnyDigits digitsTest = new AnyDigits(42339);
digitsTest.printDigits();
Any comments on the organisation, style and formatting of my code are also welcomed.
Any help gratefully received!
for(int i = this.ns.length - 1; i == 0; i--){
System.out.printf("%d ", this.ns[i]);
}
This won't work, you are iterating while i==0, i will never be 0 at the first loop unless this.ns.length == 1.
You need
for(int i = this.ns.length - 1; i != 0; i--){
System.out.printf("%d ", this.ns[i]);
}
or
for(int i = this.ns.length - 1; i >= 0; i--){
System.out.printf("%d ", this.ns[i]);
}
Anyway, if you want to print an array, you can just do
System.out.println(Arrays.toString(yourArray));
Another way aside from BackSlash's answer-
private static int[] makeArrayFromInt(final int val){
String temp = String.valueOf(val);
int[] digits = new int[temp.length()];
for(int i = 0; i < temp.length(); i++){
digits[i] = Integer.parseInt(temp.substring(i, i + 1));
}
return digits;
}
Test:
int[] digits = makeArrayFromInt(12234);
for(int i = 0; i < digits.length; i++){
System.out.println(digits[i]);
}