How to solve Index 1 out of bounds for length 1 - java

I have a method jsonProductItems() which return a map with String key and value.
public Map<String, String> jsonProductItems() throws IOException {
List<String> products = new ArrayList<>();
Map<String, String> productsAndIdentifier = new LinkedHashMap<>();
for (Item item : example.getItems()) {
products.add(item.getName());
}
for (int i = 0; i < products.size(); i++) {
productsAndIdentifier.put(indetifier.get(i), products.get(i));
}
System.out.println();
return productsAndIdentifier;
}
When in the same class in other method I want to do a matrix. When value from matrix is equal with a key from map returned by jsonProductItems() method, will print value of this key. But at line if(("" + sumByRemainder.get(i) + j).equals(entry.getKey())) have java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1. How to solve this problem? And why in this case it appear?
for (int i = 0; i <= rows; i++) {
System.out.print(sumByRemainder.get(i) + " ");
for (int j = 1; j <= columns; j++) {
if (i == 0) {
System.out.print(" " + j);
System.out.print(" ");
} else {
indetifier.add("" + sumByRemainder.get(i) + j);
for (Map.Entry<String, String> entry : jsonProductItems().entrySet()) {
if(("" + sumByRemainder.get(i) + j).equals(entry.getKey())){
System.out.println(jsonProductItems().get(entry.getKey()));
}else{
System.out.print("" + sumByRemainder.get(i) + j + " ");
}
}

Length of 1 means there is only an element at index 0 - so you should do something like (i - 1)

As some of the variables you have used seems unknown here for the other people like me, I think this code snippet is the culprit for your problem:
for (int i = 0; i <= rows; i++) {
System.out.print(sumByRemainder.get(i) + " ");
for (int j = 1; j <= columns; j++) {
//... your code
}
}
You can try the loops limit like this:
for (int i = 0; i < rows; i++) {
System.out.print(sumByRemainder.get(i) + " ");
for (int j = 1; j < columns; j++) {
// you code here
}
}
Just give a check in your looping limit for both of the loops.

Related

How to print the index number of an element in two dimensional arrays in java?

So this is the code, i displayed a multiple of 5 and then shuffled it.
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class TwoDimensionalArrays {
public static void main(String[] args) {
This part is the display of multiple of 5 numbers up to 500.
int [][]table = new int[10][10];
int x = 5;
for(int i = 0; i < table.length; i++){
for(int j=0; j < table[i].length; j++){
table[i][j]= x;
x+=5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
This part is the shuffled arrays using Math.random.
System.out.println("\nShuffled Arrays: \n");
int index1 = 0;
for(int a = 0; a < table.length; a++) {
for(int b = 0; b < table[a].length; b++) {
int il = (int)(Math.random()*table.length);
int jl = (int)(Math.random()*table[a].length);
int temp = table[a][b];
table[a][b] = table[il][jl];
table[il][jl] = temp;
System.out.print(table[a][b] + "\t");
}
System.out.println();
}
}
}
How can i print the index number of an element, for example, 40, from the shuffled arrays?
Please check the below answer. Here I added seperate for loops to print the shuffled array. Because in your current implementation after printing table[a][b] value, that value can be gain replaced by the randomly generated indexes. So Best way is print the shuffled array after completely shuffled it. Used Map<String, Integer> to keep the indexes with values. Please check the below code:
public static void main(String[] args) {
int[][] table = new int[10][10];
int x = 5;
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = x;
x += 5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
System.out.println("\nShuffled Arrays: \n");
Map<String, Integer> map = new HashMap<>(); //Hash map to keep indexes
//Shuffle the array
for (int a = 0; a < table.length; a++) {
for (int b = 0; b < table[a].length; b++) {
int il = (int) (Math.random() * table.length);
int jl = (int) (Math.random() * table[a].length);
int temp = table[a][b];
table[a][b] = table[il][jl];
table[il][jl] = temp;
}
}
//Print shuffled array
for (int a = 0; a < table.length; a++) {
for (int b = 0; b < table[a].length; b++) {
int value = table[a][b];
System.out.print(value + "\t");
//Insert indexes to hash map as key value pairs
String key = a + ", " + b;
if (value == 40 || value == 320 || value == 450) {
map.put(key, value);
}
}
System.out.println();
}
//Printing indexes
System.out.println("\nIndexes: \n");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getValue() + " [" + entry.getKey() + "]");
}
}
So the idea here is to check if value on random index is present in existing array(before shuffled), if yes then add the random entry into a map with value as newly assigned index in shuffled array, so this way once your shuffled array is ready, you have the completed map with all the details of each value and its index in shuffled array
public static void main(String [] args) {
int [][]table = new int[10][10];
Map<Integer,String> map = new HashMap<>();
int x = 5;
for(int i = 0; i < table.length; i++){
for(int j=0; j < table[i].length; j++){
table[i][j]= x;
x+=5;
System.out.print(table[i][j] + "\t");
}
System.out.println();
}
System.out.println("\nShuffled Arrays: \n");
int index1 = 0;
for(int a = 0; a < table.length; a++) {
for(int b = 0; b < table[a].length; b++) {
int il = (int)(Math.random()*table.length);
int jl = (int)(Math.random()*table[a].length);
int temp = table[a][b];
if(exists(table[il][jl], table)) {
map.put(table[il][jl], "["+a + "][" + b + "]");
}
table[a][b] = table[il][jl];
table[il][jl] = temp;
System.out.print(table[a][b] + "\t");
}
System.out.println();
}
System.out.println(map);
}
public static boolean exists(int value, int[][] tmp) {
List<int[]> list = Arrays.asList(tmp);
for(int[] arr: list){
if(Arrays.stream(arr).anyMatch(i -> i == value)) {
return true;
}
}
return false;
}
Hope this will help..!!

Print a message only once after iterating 2d array

import java.util.Scanner;
public class Note {
public static void main(String[] args) {
String etudiants[][] = new String[1][4];
Scanner saisie = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
System.out.print("\n\nEtudiant BTI00" + (i + 1) + "\n\n");
for (int j = 0; j < 4; j++) {
if (j == 0) {
System.out.print("\n\tCode de l'etudiant : ");
} else if (j == 1) {
System.out.print("\n\tNom etudiant : ");
} else if (j == 2) {
System.out.print("\n\tNote Maths : ");
} else if (j == 3) {
System.out.print("\n\tNote Francais : ");
} else {
System.out.print("\n\tChamps inexistant!");
}
etudiants[i][j] = saisie.nextLine();
}
}
System.out.print("\n\tEtudiants Enregistres : \n\n");
// System.out.print("\tCode\tNom\t\tMaths\tFrancais\n\n");
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 4; j++) {
System.out.print("\t" + etudiants[i][j] + " ");
}
}
System.out.println();
System.out.print("\n\tEntrez code etudiant : ");
String recherche = saisie.nextLine();
boolean trouve = false;
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 4; j++) {
if (recherche.equals(etudiants[i][0])) {
trouve = true;
System.out.print("\n\tCode etudiant correct!");
String math = etudiants[i][2];
String francais = etudiants[i][3];
Double m = new Double(math);
double mathConv = m.doubleValue();
Double f = new Double(francais);
double francaisConv = f.doubleValue();
double moyenne = (mathConv + francaisConv) / 2;
System.out.print("\n\tMoyenne de l'etudiant : " + moyenne);
System.out.print("\n\tEtudiant : " + etudiants[i][j]);
if (moyenne <= 40) {
System.out.print("\n\tEchec!");
} else if (moyenne > 40 && moyenne < 70) {
System.out.print("\n\tReprise!");
} else {
System.out.print("\n\tSucces!");
}
} if (!trouve) {
System.out.print("\n\tCode etudiant incorrect!");
}
}
}
}
}
I need to display only one message after entering the code etudiant but istead it displays the message 4 times. The loop should only iterate through the first column of each line and compares it to what the user entered.
The indexing variable (j) of the last inner for-loop (for (int j = 0; j < 4; j++) {) is never used inside the loop, so you actually do not need that loop at all. General styling issues of your sample aside, you should rewrite the last loop like this:
for (int i = 0; i < 1; i++) {
// throw away this
//for (int j = 0; j < 4; j++) {
if (recherche.equals(etudiants[i][0])) {
trouve = true;
// ... rest of the code like you currently have it
// You probably do not need this line too,
// because you have almost the same in your second loop
//System.out.print("\n\tEtudiant : " + etudiants[i][j]);
}
}

Stopping an inner loop after one correct iteration

The problem in the code is in the goldbach method. I want to stop iteration of the inner two loops after the inner most loop has found one pair of numbers, but I am not getting how to exit just those two loops. In other words, I only want to find only one pair per i integer created by the outermost for loop, and then move on to the next integer i.
Below is my code:
import java.util.Arrays;
import java.awt.List;
import java.util.ArrayList;
// finding prime numbers using sieve of Eratosthenes and golbach's conjecture
public class Test {
public static void main(String[] args) {
int[] num = new int[1000000];
for (int i = 2; i <= num.length; i++) {
num[i - 1] = i;
}
Test.sieve(num);
Test.goldbach(num);
}
public static void sieve(int[] array) {
for (int i = 2; i < Math.sqrt(array.length); i++) {
if (array[i - 1] == 0) {
continue;
}
for (int j = 2 * i; j <= array.length; j += i) {
array[j - 1] = 0;
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {
//System.out.print(array[i] + " ");
}
}
//System.out.println(Arrays.toString(array));
}
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break;
}
}
}
}
}
}
You could set the value of j in your second loop. eg.
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
j = i + 1; // This will end the outer loop as well.
break;
}
}
}
}
use a label to break (or continue) a loop other than the inner one:
found:
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break found;
}
}
}
or use an additional method and return - more indicated if that new method has an own clear function (and better name)
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
primeAdd(i);
}
}
private static void primeAdd(int i) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
return;
}
}
}
but, as already commented by bureaquete, there is no need for the inner loop since it is always being terminated.

Program to generate a matrix defined by user in java

guys!
First of all, I'm from Brazil, so sorry if I make some grammar error.
I'm having problems to solve an exercise in whitch I have to a program that generates a matix in java with user-informed dimensions. Then, it has to fill the matrix with values ​​which are also entered by the user. My code stops of running in my second for, passing by the columns. I get a ArrayIndexOutOfBoundException. Can you help me to see what I'm doing wrong?
import java.util.Scanner;
public class DiagonalsSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] matrix;
int[] sizes = new int[2];
int diagonalsSum = 0, i, j, n, m;
for(i = 0; i < 2; i++){
n = i + 1;
System.out.println("Inform the " + n + " dimension of the matrix");
sizes[i] = s.nextInt();
}
matrix = new int[sizes[0]][sizes[1]];
for(i = 0; i < matriz.length; i++){
n = i + 1;
System.out.println(n);
for(j = 0; j < matrix[sizes[0]].length; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
s.close();
i = 0;
j = 0;
while(i < matrix.length && j < matrix[sizes[1]].length){
diagonalsSum += matrix[i][j];
i++;
j++;
}
i = 0;
j = (matrix[sizes[i]].length - 1);
while(i < matrix.length && j > 0){
diagonalsSum += matrix[i][j];
i++;
j--;
}
System.out.println("The sum of the primary and secondary diagonals is " + diagonalsSum);
}
Thanks in advance, guys!
Try this:
for(i = 0; i < matrix.length; i++){
matrix[i] = new int[sizes[1]];
n = i + 1;
System.out.println(n);
for(j = 0; j < matrix[sizes[0]].length; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
Java's an object-oriented language. You'll do better if you encapsulate the behavior you need in a proper Matrix class.
I think there are a couple of errors in here, but I'll address the one you've asked about.
I believe
for(j = 0; j < matrix[sizes[0]].length; j++)
will always result in going out of bounds because you've declared:
matrix = new int[sizes[0]][sizes[1]];
Note that Java has 0 based indexing, meaning that for any array, array[array.length] will be out of bounds. This type of access is effectively what your for loop is doing.
for(j = 0; j < matrix[sizes[0]-1].length; j++)
should fix the column loop issue.
guys!
I changed some things and it worked!
Thanks for all the help!
import java.util.Scanner;
public class DiagonalsSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] matrix;
int[] sizes = new int[2];
int diagonalsSum = 0, i, j, n, m;
for(i = 0; i < 2; i++){
n = i + 1;
System.out.println("Inform the " + n + " dimension of the matrix");
sizes[i] = s.nextInt();
}
matrix = new int[sizes[0]][sizes[1]];
for(i = 0; i < sizes[0]; i++){
n = i + 1;
System.out.println(n);
for(j = 0; j < sizes[1]; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
s.close();
i = 0;
j = 0;
while(i < sizes[0] && j sizes[1]){
diagonalsSum += matrix[i][j];
i++;
j++;
}
i = 0;
j = (sizes[1] - 1);
while(i < sizes[0] && j > -1){
diagonalsSum += matrix[i][j];
i++;
j--;
}
System.out.println("The sum of the primary and secondary diagonals is " + diagonalsSum);
}

Printing for value of ArrayList Integer

I'm working on a small game that essentially has piles of coins, and you must take some coins from a pile then the program prints out the resulting piles in the format:
Pile 1: ****
Pile 2: *****
Pile 3: **
I have an array list that store all these values like so:
List<Integer> coins = new ArrayList<>();
[4,5,2]
But I can't figure out how to get it to properly print the *'s.
How can I write this code to print out a * for each value in an element. IE 4 *'s if the element value is 4?
Here is my current method:
static void printGameState(){
for(int i = 0; i <= coins.size()-1; i++){
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j <= coins.indexOf(i); j++){
System.out.print("*");
}
}
}
Instead of using this condition:
j <= coins.indexOf(i);
Use this condition:
j < coins.get(i);
Try it:
for(int i = 0; i <= coins.size()-1; i++) {
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j < coins.get(i); j++) {
System.out.print("*");
}
System.out.println();
}
You'll get:
Pile 1: ****
Pile 2: *****
Pile 3: **
You should be using < instead of <=. Also, you should be able to use get(i) to take the value at index i.
static void printGameState(){
for(int i = 0; i < coins.size(); i++){
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j < coins.get(i); j++){
System.out.print("*");
}
}
}
You could also make it a bit cleaner by forming another method to print * such as:
public void ast(int n){
for(int i=0; i<n; i++){
System.out.print("*");
}
}
Then the contents of printGameState loop would be
int k = i+1;
System.out.print("Pile " + k + ": ");
ast(coins.get(i));
You have to look at the values of the different stacks by accessing the array coins[i] instead of using the number of stacks as stack height:
static void printGameState(){
for(int i = 0; i < coins.size(); i++) {
// Build the coin stack
String coinStack = "";
for(int j = 0; j < coins.get(i); j++) {
coinStack += "*";
}
// And output it
System.out.println("Pile " + (i + 1) + ": " + coinStack);
}
}

Categories

Resources