How can I sum these two arrays into a new one? - java

How can I sum these two arrays into a new one? Where the first value of the arrayA sums the first value of the arrayB?
public class Exercises {
static BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
static PrintStream out = System.out;
public static void main(String[] args) throws IOException {
int numbersA[] = new int[5];
int numbersB[] = new int[5];
int numbersC[] = new int[5];
for (int i = 0; i < 5; i++) {
out.print("Please insert a number for the first array: ");
numbersA[i] = Integer.parseInt(in.readLine());
}
for (int i = 0; i < 5; i++) {
out.print("Please insert a number for the second array: ");
numbersB[i] = Integer.parseInt(in.readLine());
}
int j = 0;
for (int i = 0; i < 5; i++) {
numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
}
{
out.print("The sum of the two arrays are: " + numbersC[j] + " ");
}
out.println();
}
}

You were pretty close. numbersA[i] and numbersB[i] (not the length of each array). Also, you don't need j and should print the prelude before the loop. Like,
out.print("The sum of the two arrays are: ");
for (int i = 0; i < 5; i++) {
numbersC[i] = numbersA[i] + numbersB[i];
out.print(numbersC[i] + " ");
}
out.println();
Finally, your code relies on magic numbers (hard coded array lengths). That is bad practice, instead you should use the array.length so your code doesn't require changing when your array sizes change. Like,
int[] numbersA = new int[5];
int[] numbersB = new int[5];
for (int i = 0; i < numbersA.length; i++) {
out.print("Please insert a number for the first array: ");
numbersA[i] = Integer.parseInt(in.readLine());
}
for (int i = 0; i < numbersB.length; i++) {
out.print("Please insert a number for the second array: ");
numbersB[i] = Integer.parseInt(in.readLine());
}
int[] numbersC = new int[Math.min(numbersA.length, numbersB.length)];
out.print("The sum of the two arrays are: ");
for (int i = 0; i < numbersC.length; i++) {
numbersC[i] = numbersA[i] + numbersB[i];
out.print(numbersC[i] + " ");
}
out.println();

try to delete the numbersC[j] = (numbersA.length[i] + numbersB.length[i]);
length from both
use this shape
numbersC[i] = numbersA[i] + numbersB[i];
i think it will be work now

Related

Problem With Reversing Each Number In An Array In Java

I'm trying to reverse each number in an Integer array using do-while, but I get NullPointerException error.I'm trying to reverse each element in this array: for instance if this is my array:{12,34,56} then the result must be:{21,43,65}.Can someone please help me with this?
public class Reverse {
public int[] revCalculator(int[] number) {
int[] reverse = null;
for (int j = 0; j < number.length; j++) {
do {
reverse[j] = reverse[j] * 10 + number[j] % 10;
number[j] /= 10;
} while (number[j] > 0);
}
return reverse;
}
}
public class ShowReverse {
public static void main(String[] args) {
// instantiation
// -----------------------------------------
Reverse rev = new Reverse();
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Enter The Number Of Elements: ");
int len = in.nextInt();
int[] numbers = new int[len];
for (int i = 0; i < len; i++) {
System.out.println("Enter Number: ");
numbers[i] = in.nextInt();
}
int[] result = rev.revCalculator(numbers);
// shows the result
// -----------------------------------------
System.out.println("THE REVERSE WOULD BE: ");
System.out.print(result);
}
}
pic
You didn't initialize your variable reverseArray, initialize it like so:
UPDATE, I see what you are trying to do, you want to reverse the values of your array, not the array itself
public int[] revCalculator(int[] number) {
int[] reverse = new int[number.length]; //Initialize it to the same size as the passed in arary
//int[] reverse = null; //Problem
StringBuilder sb = new StringBuilder();
for (int j = 0; j < number.length; j++)
{
//You could convert the number to string then reverse it and use parseInt() int
reverse[j] = parseInt(sb.append(number[j].toString()).reverse().toString());
//Clear the StringBuilder object
sb.setLength(0);
}
return reverse;
}
I would recommend initializing the reverse array to an array of the same length as the number array.
int[] reverse = new int[number.length];
There are a couple of changes that you have to make:
initialize reverse array int[] reverse = new int[number.length];
System.out.print(result); would give you the address of result array. You have to show the elements of the array.
int[] result = new int[numbers.length];
result = rev.revCalculator(numbers);
// shows the result
// -----------------------------------------
System.out.println("THE REVERSE WOULD BE: ");
//System.out.print(result);
for(int i = 0 ; i<result.length; i++)
System.out.println(result[i]);
Hope this helps.

Extract numbers from a array and divide them (positives and negatives) into separate arrays

I want to extract numbers from an array and divide them into positives and negatives into separate arrays. Why does my Java code does not work?
How to make it work?
int pole[] = new int[20];
int pock = 0;
int pocz = 0;
int pocn = 0;
for (int i = 0; i < pole.length; i++) {
pole[i] = (int)(-10+Math.random()*21);
}
for (int i = 0; i < 10; i++) {
if(pole[i]>0)pock++;
else if(pole[i]<0) pocz++;
else pocn++;
}
int pklad[] = new int[pock];
int pzap[] = new int [pocz];
int n[] = new int [pocn];
int j = 0;
for (int i = 0; i < pole.length; i++) {
if(pole[i]>0){
pklad[j] = pole[i];
}if(pole[i]<0){
pzap[j] = pole[i];
}else n[j]=pole[i];
j++;
}
System.out.print("All positives: ");
for (int i = 0; i < pock; i++) {
System.out.print(pklad[i]+",");
}
System.out.println();
System.out.print("All negatives: ");
for (int i = 0; i < pocz; i++) {
System.out.println(pzap[i]);
}
System.out.print("Zeros: ");
for (int i = 0; i < pocn; i++) {
System.out.println(n[i]);
}
Edit: This throws an exception: (thanks, BRjava)
ArrayIndexOutOfBoundsException, line 36
Use the ArrayList it is better than normal arrays.
public static void main(String[] args) {
ArrayList<Double> yourNumbers = new ArrayList<Double>();
yourNumbers.add(54.2); //add some number to our array
yourNumbers.add(-67.7);
ArrayList<Double> positive = new ArrayList<>();
ArrayList<Double> negative = new ArrayList<>();
for(Double currentNumber : yourNumbers) {
if(currentNumber >= 0) {
positive.add(currentNumber);
}else if(currentNumber <0) {
negative.add(currentNumber);
}
}
//print all positive numbers
for(Double currentDouble : positive) {
System.out.println("Positive: "+currentDouble);
}
//print all negative numbers
for(Double currentDouble : negative) {
System.out.println("Negative: "+currentDouble);
}
}
The problem is that you have three arrays, pklad[], pzap[], and n[], but you try using a single index j to write to all three. This is what is causing your ArrayIndexOutOfBoundsException: as soon as j goes past the limit of the shorter of the arrays, an attempted write causes the exception.
You need three separate indexes, say, jpos, jneg, and jn, all initialized to zero before the loop. Each index needs to be incremented individually when you write to its corresponding array:
for (int i = 0; i < pole.length; i++) {
if (pole[i] > 0) {
pklad[jpos++] = pole[i];
} else if (pole[i] < 0) {
pzap[jneg++] = pole[i];
} else {
n[jn++]=pole[i];
}
}

Java: Output Array in Reverse Order

I am new to Java and working with arrays. Also new to this site. Trying to output my array in reverse order:
import java.util.Scanner;
public class ListingTest
{
public static void main (String[] args)
{
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many names will you enter?");
length = input.nextInt();
String[] names = new String[length];
int[] ages = new int[length];
for(int counter = 0; counter < length; counter++)
{
System.out.println("Enter name " +(counter+1));
names[counter] = input.next();
System.out.println("Enter age " +(counter+1));
ages[counter] = input.nextInt();
}
input.close();
for(int counter = 0; counter < length; counter++)
{
System.out.println("Name: " +names[counter]+ " Age: "+ages[counter]);
}
}
}
Having trouble with the last "for loop." Any help is appreciated.
Thank you.
for (int i = names.length - 1; i >= 0 ; i--) {
System.out.println("Name: " + names[i] + " Age: " + ages[i]);
}
This starts at the top of the array and decrements i by 1 every iteration.
Just for printing Array at reversed order you have to use following:
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
}
Or can use Commons Lang library:
ArrayUtils.reverse(arr)

Merge sort 3 way java

I have to make a 3 way merge sort of an array. the array length is a in a power of 3, i.e. 3,9,27 etc. So I can use only one split function and not "left","mid","right".
Would like to get an answer how to repair it and why does not it work.
I have written the code, however don't know how to get it to work.
Here it is:
EDITED THE CODE, STILL DOES NOT WORK
public class Ex3 {
public static void main(String[] args) { //main function
Scanner in = new Scanner(System.in); //scanner
int size = in.nextInt();
int[] arr = new int[size];
for (int i = 0; i<arr.length; i++){
arr[i] = in.nextInt();
}
in.close();
arr = merge3sort (arr); //send to the function to merge
for (int i = 0; i<arr.length; i++){ //printer
System.out.print(arr[i]+ " ");
}
}
static int[] split(int[] m, int thirdNum) { //split function that splits to 3 arrays
int third[] = new int[m.length/3];
int third1[]=new int[m.length/3];
int third2[]=new int[m.length/3];
for(int i = 0; i<=m.length/3; i++)
third[i]=m[i];
for(int i=0; i<=m.length/3;i++)
third1[i]=m[i+thirdNum];
for(int i=0; i<=m.length/3;i++)
third2[i]=m[i+2*thirdNum];
return merge(third,third1,third2);
//return null;
}
static int minOf3(int[] a3) { //function that finds out how what is the index of the smallest number
int num0 = a3[0];
int num1 = a3[1];
int num2 = a3[2];
int idx = 0;
if(num0<num1 && num1<num2)
idx=0;
if(num1<num0 && num0<num2)
idx=1;
else
idx=2;
return idx;
}
static int[] merge(int[] th0, int[] th1, int[] th2) { //function that sorts the numbers between 3 arrays
int len0=th0.length;
int len1=th1.length;
int len2=th2.length;
int[] united = new int[len0+len1+len2];
int ind = 0; int i0=0; int i1=0; int i2=0;
while(i0<len0 && i1<len1 && i2<len2){
if(th0[i0]<th1[i1]){
if(th0[i0]<th2[i2]){
united[ind]=th0[i0];
i0=i0+1;
}//end inner if
else{
united[ind]=th2[i2];
i2=i2+1;
}//end inner else
}//end outer if
else{
united[ind]=th1[i1];
i1=i1+1;
}//end outer else
ind=ind+1;
}//end while
for (int i = i0; i < len0; i = i + 1) {
united[ind] = th0[i];
ind = ind + 1;
}
for (int i = i1; i < len1; i = i + 1) {
united[ind] = th1[i];
ind = ind + 1;
}for (int i = i2; i < len2; i = i + 1) {
united[ind] = th2[i];
ind = ind + 1;
}
return united;
}
static int[] merge3sort(int[] m) { //function that glues all together
if (m.length == 1) {
return m;
}
else{
return merge(merge3sort(split(m,m.length/3)),merge3sort(split(m,m.length/3)),merge3sort(split(m,m.length/3))); }
}
I get the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ololosh1.Ex3.split(Ex3.java:27)
at ololosh1.Ex3.merge3sort(Ex3.java:98)
at ololosh1.Ex3.main(Ex3.java:15)
Look at this part of your code:
for(int i = 0; i<=m.length/3; i++)
third[i]=m[i];
for(int i=0; i<=m.length/3;i++)
third1[i]=m[i+thirdNum];
for(int i=0; i<=m.length/3;i++)
third2[i]=m[i+2*thirdNum];
Arrays are indexed from 0 to length-1. Each third* array has length m.length/3. Therefore their index can only go up to m.length/3 - 1. Yet you are indexing up to and including m.length/3.
Once you get your application working correctly, you really should clean it up. There is a lot of redundancy. For example, you are using the expression m.length/3 multiple times in method split() but you are also passing that same value to it as an argument.

10 element Array will only accept 5 integers during Selection sort project

Ok, so this is for a Java class, but I'm not looking for someone to write the code, just help me debug this one. I want to enter 10 integers and have the inputs sorted in ascending order as they are entered then displayed, without any zeros (0) that may exist in the array.
Example of what the assignment should look like:
Enter 10 integers - one at a time...
Enter integer #1: 21
Sorted numbers: 21
Enter integer #2: 48
Sorted numbers: 21 48
Enter integer #3: 37
Sorted numbers: 21 37 48
etc....
I have tried a Selection Sort, Insertion and Bubble Sort, but the array will not hold or display more than 5 numbers.
Help.
Here is my Main:
import java.util.*;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int j = 1;
int[] list = new int[10];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length; i++){
System.out.print("Enter integer #" + j + ": ");
list[i] = input.nextInt();
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for(int p= 0; p<list.length; p++){
if (list[p] !=0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}
Here is my Selection Sort:
public class SelectionSort {
public static void sort (int[] list){
for(int i=0; i<list.length; i++)
{
for(int j=i+1; j<list.length; j++)
{
if(list[i] > list[j] )
{
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
}
}
Thanks in advance!
Why don't you use List insteed of array and ready-to-go sorting implementations from jdk -> Collections.sort() ?
Anyway the problem is that you are inserting new integers into already sorted array and that causes disfunction of your code. So as you inserting new elements on indexes 0,1,2,3,4 - sorting algorithm moves them to positions 5,6,7,8,9. From this point your inputs starts overriding sorted values with new ones from input - (Main loop i>=5).All in all, it accepted 10 integers, but 5 of them where kindly overriten.
Here is little modified version of your work whitch works like you want. Analyze it!
import java.util.*;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int j = 1;
int[] list = new int[11];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length - 1; i++) {
System.out.print("Enter integer #" + j + ": ");
list[0] = input.nextInt();
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for (int p = 1; p < list.length; p++) {
if (list[p] != 0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}
class SelectionSort {
public static void sort(int[] list) {
for (int i = 0; i < list.length; i++) {
for (int j = i + 1; j < list.length; j++) {
if (list[i] > list[j]) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
i--;
break;
}
}
}
}
}
You are replacing sorted value with list[i] = input.nextInt(); with every input. So, 5 values always 0 in list. Use List<Integer> instead of int[] and add new value to List<Integer>. Try following code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
int j = 1;
List<Integer> list = new ArrayList<>();
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < 10; i++){
System.out.print("Enter integer #" + j + ": ");
list.add(input.nextInt());
j++;
//SortMethod.sort(list, list.length);
// SelectionSort.sort(list);
Collections.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for(int p= 0; p<list.size(); p++){
if (list.get(p) !=0)
System.out.print(list.get(p) + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
I just modified the lines below the comments I put (temp declaration and for loop).
This changes makes program support negative numbers too, read the comments below:
import java.util.*;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int j = 1;
int[] list = new int[11];
System.out.println("Enter 10 integers - one at a time...");
for (int i = 0; i < list.length - 1; i++) {
System.out.print("Enter integer #" + j + ": ");
// Add temporal variable to store input
int temp = input.nextInt();
// Check for empty place in list (as far as it seems you don't care about zeros)
for (int p = 0; p < list.length; p++) {
if (list[p] == 0) {
list[p] = temp;
break;
}
}
j++;
//SortMethod.sort(list, list.length);
SelectionSort.sort(list);
//BubbleSort.sort(list);
System.out.print("Sorted numbers: ");
for (int p = 1; p < list.length; p++) {
if (list[p] != 0)
System.out.print(list[p] + " ");
}
System.out.print("\n");
}
System.out.println("Done!");
}
}

Categories