Out of bounds exception multiplying arrays - java

As far as my knowledge goes, this program is done correctly. However, given the exception it appears not. I am to make 2 arrays of length x (user inputted) and the user is to input the elements. Done. Next multiply each element by its corresponding element in the other array and add the sum total.
Ex, array1[0]*array2[0] + array1[1]*array2[1]...
Precise error is : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
I have done many different loops, the last loop below that I have spaced extra to identify is what I think is closest to correct but not. I would much appreciate some advice, thank you in advance.
System.out.println("This program will multiply 2 one dimension arrays of any length. \n The length and contents of the array is entered from the keyboard.");
System.out.println("Enther the data for the first array. ");
System.out.println("Enther the length of the array (remember arrays being counting at 0, not 1:");
int a = 0;
Scanner keyboard = new Scanner(System.in);
a = keyboard.nextInt();
int[] firstArrayLength = new int[a];
System.out.println("Enter the elements of the first array(remember arrays begin counting at 0, not 1");
double arrayElements = 0;
for (int elements = 0; elements <= firstArrayLength.length; elements++) {
arrayElements = keyboard.nextInt();
}
System.out.println("Enter the data for the second array. ");
System.out.println("Enter the elements of the second array(remember arrays begin counting at 0, not 1");
int[] secondArrayLength = new int[a];
double secondArrayElements = 0;
for (int elements = 0; elements <= secondArrayLength.length; elements++) {
secondArrayElements = keyboard.nextInt();
}
double [] thirdArray = new double [a];
for (int i =0; i <=firstArrayLength.length; i++)
{
thirdArray[a] = firstArrayLength[i]*secondArrayLength[i];
}
System.out.println(thirdArray);
}

Change your <= symbols to < when you are accessing de array. For instance:
for (int elements = 0; elements < firstArrayLength.length; elements++)
...
Remember if the length is 4, you can access elements as:
array[0], array[1], array[2], array[3] // 4 elements
array[4] doesn't exist, that cause the IndexOutOfBounds exception.
Edit
The strange output [I#756a7c99 (for instance) is because you are printing an array as:
int a[] = new int[4];
System.out.println(a);
Instead, you may want to print elements of that array:
int a[] = new int[4];
for (int i = 0; i < 4; i++) {
System.out.println(a[i]);
}
Edit 2
public static void main(String[] args) {
System.out
.println("This program will multiply 2 one dimension arrays of any length. \n The length and contents of the array is entered from the keyboard.");
System.out.println("Enther the data for the first array. ");
System.out
.println("Enther the length of the array (remember arrays being counting at 0, not 1:");
int a = 0;
Scanner keyboard = new Scanner(System.in);
a = keyboard.nextInt();
int[] firstArray = new int[a];
System.out
.println("Enter the elements of the first array(remember arrays begin counting at 0, not 1");
for (int elements = 0; elements < firstArray.length; elements++) {
firstArray[elements] = keyboard.nextInt();
}
System.out.println("Enter the data for the second array. ");
System.out
.println("Enter the elements of the second array(remember arrays begin counting at 0, not 1");
int[] secondArray = new int[a];
for (int elements = 0; elements < secondArray.length; elements++) {
secondArray[elements] = keyboard.nextInt();
}
double[] thirdArray = new double[a];
for (int i = 0; i < firstArray.length; i++) {
thirdArray[i] = firstArray[i]*secondArray[i];
}
for (int i = 0; i < thirdArray.length; i++)
System.out.println(thirdArray[i]);
}

elements <= firstArrayLength.length ==> elements < firstArrayLength.length
arrayElements = keyboard.nextInt(); ==>> firstArrayLength[elements] = keyboard.nextInt();
secondArrayElements = keyboard.nextInt(); ==>> secondArrayLength[elements] = keyboard.nextInt();

Related

Printing an integer array in java using for loop, but the first element is always zero

I have been trying for hours to change a user inputted string of numbers into an integer, then create and print an integer array with those integers. I finally got it, but the first element of the printed array is always zero. I don't know how to fix it. I feel like it is really simple, but I am exhausted and am getting stuck on the easiest things. Does anyone know what is wrong? I'll put my code below.
String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];
for (int a : myArray) {
System.out.print(a);
System.out.print(" ");
for (int i = 0; i < size; i++) {
char n = stringNum.charAt(i);
int intNum = Character.getNumericalValue(n);
myArray[i] = intNum;
}
}
// input: 12345
// output: 0 2 3 4 5
You have mixed up printing the array and populating the array.
First, parse the input string and populate the array
String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];
for (int i = 0; i < size; i++) {
char n = stringNum.charAt(i);
int intNum = Character.getNumericalValue(n);
myArray[i] = intNum;
}
Then print the elements,
for (int a : myArray) {
System.out.print(a);
System.out.print(" ");
}

two arrays from user input and get an output of the common values of the two arrays

I'm still new to java and been trying to write code that takes two different arrays of common values and outputs the common values of both arrays but I keep getting the following error message:
Exception in thread "main" Your common values are: 0 Your common
values are: 0 Your common values are: 0 Your common values are: 0
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for
length 5 at HomworkTestingQ.main(HomworkTestingQ.java:18)
Scanner sc = new Scanner(System.in);{
int n = 5;
int m = 5;
int[] array1 = new int[m];
int[] array2 = new int[n];
System.out.println("Enter the first array: ");
n=sc.nextInt();
System.out.println("Enter the second array");
m=sc.nextInt();
for(int i = 0; i < array1.length; i++) {
for(int j = 0; i < array2.length; j++) {
if(array1[i] == array2[j]) {
System.out.println("Your common values are: " + array1[i+j] );
}
}
}
}
}
}
I fix your codes:
Scanner sc = new Scanner(System.in);
int n = 5;
int m = 5;
int[] array1 = new int[m];
int[] array2 = new int[n];
System.out.println("Enter the first array: ");
for (int i = 0; i < n; i++) {
array1[i] = sc.nextInt();
}
System.out.println("Enter the second array");
for (int i = 0; i < n; i++) {
array2[i] = sc.nextInt();
}
for (int item : array1) {
for (int value : array2) {
if (item == value) {
System.out.println("Your common values are: " + item);
}
}
}
I believe the issue is that you're adding the array iterators here:
array1[i+j]
The i+j is adding to be more than the length of array1.
An aside, your arrays aren't being populated as I think you expect based on:
System.out.println("Enter the first array: ");
n=sc.nextInt();
System.out.println("Enter the second array");
m=sc.nextInt();
I'm just speculating there perhaps you have more to do there down the line.
You don't need to add up the indices..
Since array1[i] is equal to array2[j], print any one of them:
for(int i=0;i<array1.length;i++){
for(int j=i+1;j<array2.length;j++){
if(array1[i]==array2[j]) int commonValue = array1[i];
return commonValue; // or print it
}
}
FIRST PROBLEM
The size of the array won't change when you scan the value of m and n because java is pass by value and the size of the array is the value, not the variable.
So you should do something like-
int m = scanner.nextInt();
int[] arr = new int[m];
SECOND PROBLEM
System.out.println("Your common values are: " + array1[i+j] );
This will go out of bounds, perhaps you should do-
System.out.println("Your common values are: " + array1[i] );

Merging/Sorting My Array (Java)

What I need to do is ask the user to input values for two arrays and then output them separately and also output a merged array that is in ascending order.
For example, if the user inputs 2,5,8,0 for the first array and 6,7,0 for the second array, then the merged array should output 2,5,6,7,8.
The output for my first two arrays work perfectly but the merged array always outputs a zero. I also added a restart boolean to see if the user wants to try it again. Please help me as I am stuck.
I understand the though process but not sure how to implement this into my code. Here is my code:
//import packages
import java.util.Scanner;
import java.lang.Math;
import java.util.Arrays;
public class Main4{
public static void main(String[] args){
boolean doItAgain = true;//add boolean value to use when restarting progam
Scanner scan = new Scanner (System.in);//initialize new scanner
while(doItAgain){
//initialize variables
int first [] = new int[10000];//initialize to maximum of 10,000 integers
int second [] = new int[10000];//initialize to maximum of 10,000 integers
int input1;
int input2;
int counter1 = 0;//counter variable for first string
int counter2 = 0;//counter variable for second string
System.out.println("");
System.out.println("Welcome To my Merge Array Program 2.0!");
System.out.println("Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit"); //asks user for first array input
//loop to go through each index
for (int a = 0; a<10000; a++)
{
input1 = scan.nextInt();//stores input as input1
first [a] = input1;
counter1++;
if (input1<=0)
break;//breaks out of loop if input1 value is 0 or below
}
int first2 []= new int [counter1-1];
for(int b = 0; b<first2.length; b++) {
first2 [b] = first[b];
}
System.out.println("Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit"); //asks user for second array input
for (int j = 0; j<10000; j++)
{
input2 = scan.nextInt();//stores input as input2
second [j] = input2;
counter2++;
if (input2<=0)
break;//breaks out of loop if input1 value is 0 or below
}
int second2 []= new int [counter2-1];
for(int c = 0; c<second2.length; c++) {
second2 [c] = second[c];
}
System.out.println("First Array:");//output first array values in the order of their input
for (int p=0; p<first2.length; p++) {
System.out.print(first2[p] + " ");
}
System.out.println("\nSecond Array:");//output second array values in the order of their input
for (int p2=0; p2<second2.length;p2++) {
System.out.print(second2[p2] + " ");
}
boolean valid = true;
for (int e = 0; e<first2.length-1; e++) {
if(first2[e]>first2[e+1]) {
valid = false;
}
}
for (int e2 = 0; e2<second2.length-1;e2++) {
if(second2[e2]>second2[e2+1]) {
valid = false;
}
}
int[] array = new int[first2.length + second2.length];
//fill array 3 with arrays 1 & 2
for(int k = 0; k <first2.length;k++){
array[k] = first2[k];
}
for (int l = 0; l<second2.length; l++){
array[first2.length + l] = second2[l];
}
//sort array 3
for (int i = 0; i<first2.length + 1; i++){
for (int j = i+1; j<first2.length + 1; j++){
if(array[i] > array[j]){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//output sorted merged array
System.out.println("\nMerged Array: ");
for(int p3 = 0; p3<array.length; p3++) {
System.out.print(array[p3] + " ");
}
//Asks user if they want to restart program. Used boolean value to initialize doItAgain variable
System.out.println("");
System.out.println("");
System.out.println("Thanks for using this program! Do you want to do it again? (Y or N)");
if(scan.next().toLowerCase().equals("y")){
doItAgain = true;
break;
}
else{
doItAgain = false;
System.out.println("If you change your mind and want to run it again, type runMain.");//output closing statement if user says N to restart
break;
}
}
}
}
You are not merging your arrays. Your 1st array is, for instance [1 2] and your second array is, for instance [3 4]. Your final array is going to be initialized with size 4 (first2.length + second2.length), but all it's elements will be zero.
In this line here, I suggest you use arraycopy() to fill your final array:
int[] array = new int[first2.length + second2.length];
System.arraycopy(first2, 0, array, 0, first2.length);
System.arraycopy(second2, 0, array, first2.length, second2.length);
This will copy the first2 array to the starting position of your final array and then copy your second2 array to the position of your final array where first2 ended. You will end up with [1 2 3 4] and can then sort the elements (though in this case, they're already sorted.
For more information on arraycopy() consult this page here:
https://www.tutorialspoint.com/java/lang/system_arraycopy.htm
EDIT: BTW, you have an error right here, which is what is preventing you from printing the full sorted array:
//output sorted merged array
System.out.println("\nMerged Array: ");
for(int p3 = 0; p3<array.length; p3++) {
System.out.print(array[p3] + " ");
} //right here, you need to close this curly bracket
EDIT2: Since you can't use arraycopy(), you can use for loops to fill in the final array:
for(int k = 0; k <first2.length;k++){
array[k] = first2[k];
}
for (int l = 0; l<second2.length;l++){
array[first2.length + l] = second2[l];
}

Create multiple arrays using a for loop

I would like to make a program where the user can input the number of variables and fill every variable with certain values. For example, the User inputs that he/she wants to make 10 arrays, then the User inputs that the first array should have 5 elements and the User fills that array with values, then the User wants the second array to have 4 elements and does the same and so on.
This is the code I was using, but it doesn't work:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
for(int j = 0;j < i;j++){
int[] var = new int[j];
System.out.println("Enter the number of values: ");
int p = s.nextInt();
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[q] = n;
}
}
}
And how could I compare these arrays that the user inputs?
The problem is that each time you are creating the array.
try this:
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[j][q] = n;
}
}
Instead of creating a one dimensional array, you create a jagged array. Essentially, a 2d array is an array of arrays. that way the user inputs the number of arrays (i) and then continues to fill the arrays.
To check whether two collections have no commons values, you can use
Collections.disjoint();
For other operations, you can look here
This should work (with bidimensionnal array)
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;q++){
int n = s.nextInt();
var[j][q] = n;
}
}
}
You have to replace the incrementation in the second loop too ("q++" instead of "p++")
This should work and solve their first point
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
while (p>0)
{
var[j] = new int[p];
for(int q=0;q < p;q++){
System.out.println("Value number : " +(q+1) + " For Array Number "+ (j+1));
int n = s.nextInt();
var[j][q] = n;
}
p-=1;
}
}

converting an arraylist(integer) to an integer array

I've tried couple of things to make this code work, but it didn't.
my goal is to instantiate nums[] with numbers {0, 1, 2, .... n-1}. nums has no size, so I used list that instantiate nums with zeros. Keep in mind that the result must be an array (nums).
int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();
ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros
//nums = listNum.toArray(nums);
for (int i =0; i < n; i++){
nums[i] = i;
}
When you're writing this :
ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros
listnum has a size of 0, so nums won't be initialized as you want.
Why not just do :
nums = new int[n];
?
Array's are fixed in size.
nums = new int[listNum.size()];
That never works. You are initializing your array with zero elements. Once you declare the array size, you can't change that back.
What you are looking for is
int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();
nums = new int[n];//instantiate nums with entered size
for (int i =0; i < n; i++){
nums[i] = i;
}
Just get rid of that ArrayList since you are know the size n
You don't need an ArrayList - if you take the input of n from the command line, you could just use it to initialize the array:
nums = new int[n];
for (int i =0; i < n; i++){
nums[i] = i;
}

Categories