How to add one array into another equalling another array - java

How would one go about adding the contents of one array into another array, to be equal to another array.
double[] array1 = new double[4];
double[] array2 = new double[4];
double[] array3 = new double[4];
double input;
double number1;
double number2;
System.out.println("Welcome. Please enter the first number in 1st set: ");
// add 4 numbers into 1st array
System.out.println("Please enter the first number in the 2nd set: ");
// add 4 numbers into 2nd array
for (int i = 0; i < array3.length; i++){
array3[i] = array1[i] + array2[i];
System.out.println(" #" + (i+1) + " in the array is " + array3[i]);
}
I do not know why the code at the bottom does not work. No error messages come up, just 0's in the code.
Should I do this:
int number1 = array1[1];
int number2 = array[1];
int finalNumber = number1 + number2;
finalNumber = array3[1];
That just seems unnecessarily complicated.
Edit
This is the code I use to assign the variables in the array.
System.out.println("Welcome. Please enter the first number in 1st set: ");
for (int i = 0; i < array1.length; i++){
System.out.println(i+1 + ": ");
input = TextIO.getlnDouble(); // Retrieves input
input = array1[i];
}
System.out.println("Please enter the first number in the 2nd set: ");
for (int i = 0; i < array2.length; i++){
System.out.println("Number: ");
input = TextIO.getlnDouble(); // Retrieves input
input = array2[i];
}

You are assigning values wrong way.
You should use array1[i]=input; instead of input = array1[i];.See below.
for (int i = 0; i < array1.length; i++){
System.out.println(i+1 + ": ");
input = TextIO.getlnDouble(); // Retrieves input
array1[i] = input;
}
System.out.println("Please enter the first number in the 2nd set: ");
for (int i = 0; i < array2.length; i++){
System.out.println("Number: ");
input = TextIO.getlnDouble(); // Retrieves input
array2[i] = input;
}

Your code is neat and looks fine.
Did you print and check the values of first two arrays?
Since you already had the line
double[] array3 = new double[4];
there won't be a problem with your for loop. Just print the first two arrays.

public static void main (String[] args){
double[] array1 = new double[4];
double[] array2 = new double[4];
double[] array3 = new double[4];
double input;
double number1;
double number2;
System.out.println("Welcome. Please enter the first number in 1st set: ");
array1[0] = 1;
array1[1] = 2;
array1[2] = 3;
array1[3] = 4;
for (int i = 0; i < array2.length; i++){
System.out.println("Number: ");
input = TextIO.getlnDouble(); // Retrieves input
//input = array2[i]; <--- change this to
array2[i] = input;
}
for (int i = 0; i < array3.length; i++){
array3[i] = array1[i] + array2[i];
System.out.println(" #" + (i+1) + " in the array is " + array3[i]);
}
}
and my output is
Welcome. Please enter the first number in 1st set:
Please enter the first number in the 2nd set:
#1 in the array is 2.0
#2 in the array is 4.0
#3 in the array is 6.0
#4 in the array is 8.0
maybe it helps =)

you have to change your code
for (int i = 0; i < array2.length; i++){
System.out.println("Number: ");
input = TextIO.getlnDouble(); // Retrieves input
input = array2[i]; <--- change this to
}
thats the right one
for (int i = 0; i < array2.length; i++){
System.out.println("Number: ");
input = TextIO.getlnDouble(); // Retrieves input
array2[i] = input;
}
and for the first array too

You are incorrectly assigning values to the arrays.
The variable that you want to assign a value to, goes on the left hand side of the = operator. The variable that you are assigning a value from goes on the right hand side.
Currently you are assigning the value in array1[i] to input.
Since you want to assign the value in input to a position in the array, you need to change
input = array1[i];
to
array1[i] = input;
And likewise with the second array.

Related

Adding elements of an array that was decided through user input

I'm trying to add all the elements together in an array that was decided through user input, Every time I run the code that I've constructed below I get a number that is obviously not the sum of the elements. What am I doing wrong?
import java.util.Scanner;
public class SumProduct
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
int[] array1 = new int [input.nextInt()];
input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
}
}
You probably want to prompt the user to enter the size of the array if you're going to do this.This line of code is allowing whatever the user enters to be the size of your array.
int[] array1 = new int [input.nextInt()]; //this sets the size of the array through user input
scan doesn't exist in the currrent context:
input = scan.nextInt(); // this is invalid syntax as scan is not the Scanner you created
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
I would do this to keep adding elements to the array:
// no need for this: input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
System.out.println("Enter integer to add:");
array1[i] = input.nextInt();
}
This code will give you the sum of the elements if you just add one element at a time instead of two to the sum variable:
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum += array1[i];
System.out.print(sum); // this will print out sum after each addition
}
System.out.print(sum); // this will print out sum after the entire array is summed
Adding some logic to only allow the user to enter so many numbers to the array would be helpful as well. You will need to move on from them entering data into the array at some point. Then also remember to close the scanner when you're finished getting data from the user:
input.close();
Your problem is in the following lines of code:
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
it should look something like
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum = sum + array1[i];
}
System.out.print(sum);
The first change is to declare the variable "sum" outside of the loop. The way it's written, it will get declared, then disappear, then declared, then disappear for every loop iteration. You also probably want to initialize it to 0
The second change is to your summation logic. Lets assume your array contains the three numbers [1, 2, 3] and walk through your logic.
j = array1[0] //(j == 1)
k = array1[0] + 1 //(k == 1 + 1 == 2)
sum = j + k //(sum == 1 + 2 == 3)
You then throw out the variable "sum" like I mentioned earlier, and start over with the same logic on the second array element, then again on the third.
i.e. j = 2, k = 2+1, sum = 2 + 2 + 1. followed by j = 3, k = 3 + 1, sum = 3 + 3 + 1.
You can probably see how this isn't the sum, and results in you logging the three digits 3, 5, and 7 for this example case.
In my updated logic, we simply loop through each element and add it to the current running total.
hope this helps

Java is printing last number using array method, by ignoring other numbers

I'm trying to let my code print numbers I put in output but using array method.
package pkg11;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
for (int z = 1; z <= b; z++) {
System.out.println("Input your" + " " + z + " " + "number");
x = in.nextInt();
}
System.out.println();
int[] a = new int[x];;
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
The problem is when it's printing it only prints the last value, for example, I put that I want to put 3 numbers, the first was 1 the second was 2 the third was 3, it prints the third without putting the first 2.
Have a close look at the following code fragment of yours and try to spot the error:
for (int z = 1; z <= b ; z++) {
System.out.println("Input your" +" " +z +" " +"number");
x = in.nextInt();
}
// here you create the array
int [] a = new int [x];
If you didnt spot it: You create the array you want to save each integer in after you have read all values from the console. There is no way you can store the users input in the array, since it is not known at that time.
Then, what did you actually do?
You used the same variable x all the time x = in.nextInt();, overriding each input.
What can i do to solve the problem?
Scanner in = new Scanner(System.in);
int x = 0;
System.out.println("How many number do you want to put?");
int b = in.nextInt();
int[] a = new int[b];
for (int z = 0; z < b; z++) {
System.out.println("Input your" + " " + (z + 1) + " " + "number");
a[z] = in.nextInt();
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
First, declare int[] a = new int[b]; before you read the values and assign each input the the array with a[z] = in.nextInt();. Also, i modified your loop index a little bit to make things easier.
Ok, what else can i do?
Apart from the user entering non numbers, this code is a little bit more bullet-proof! If you are looking for even more, you can use in.nextLine() and Integer.valueOf() to prevent the user from entering strings instead of numbers.
Scanner in = new Scanner(System.in);
int amountOfNumers;
System.out.println("How many number do you want to put? Amount: ");
amountOfNumers = in.nextInt();
while (amountOfNumers < 1) {
System.out.println("Please enter a number greater than one:");
amountOfNumers = in.nextInt();
}
int[] numbers = new int[amountOfNumers];
for (int i = 0; i < amountOfNumers; i++) {
System.out.println("Input your " + (i + 1) + " number: ");
numbers[i] = in.nextInt();
}
System.out.println("Your numbers are:");
Arrays.stream(numbers).forEach(System.out::println);

Java adding issue

I have an issue with my java program displaying every number it is adding, what can I do so that it only displays the total. I am guessing since I have "element" in the last part of the code it showing every single addition: Here is what I have written:
import java.util.Scanner;
public class SomeClass {
public static void main(String[]args){
int ans = 0;
int num;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many integers do you have? (Max 20)");
int x= keyboard.nextInt();
int [] element = new int[x];
for(int subscript = 0; subscript < element.length; subscript++){
System.out.println("Enter element for subscript " + (subscript));
element[subscript] = keyboard.nextInt();
}
System.out.println("Here are all of those numbers");
for(int subscript = 0; subscript < element.length; subscript++){
num = element[subscript];
System.out.println(num);
}
for (int i = 0; i < element.length; i++){
ans += element[i];
System.out.println("The sum of these numbers is " + ans);
}
}
}
//previous lines of code
for (int i = 0; i < element.length; i++){
ans += element[i];
}
System.out.println("The sum of these numbers is " + ans);
//code follows
Because You print out the 'num' as many as length of element. You have to delete that line if your intention is to show only the summed ans which is result of sumation. If you wanna show inputs then its fine
Also
Take this sentence out of the for loop
System.out.println("The sum of these numbers is " + ans);
Everytime for loops working, that line works too. So make it works once after you add all the numbers with for loop.

How To Add Indices Together Within An Array?

I am working on an assignment and I'm not sure how to add the indices together to get a sum that can be displayed. Mind you I'm only a high school student so my code is sloppier and less efficient than what any of you would likely create, but any help is appreciated. Here's what I have right now that's producing an index out of bounds exception:
System.out.println("Please enter the amount of workers you have");
Scanner userInput = new Scanner (System.in);
int workerAmount = userInput.nextInt();
int payroll[][]= new int [workerAmount][6];
for(int a = 0; a < payroll.length; a++){
for(int b = 0; b < payroll[a].length; b++)
{
System.out.println("How many hours did this worker work?");
Scanner use = new Scanner (System.in);
int user = use.nextInt();
payroll[a][b] = user;
}
}
for(int i = 0; i < payroll.length; i++){
for(int a = 0; a < payroll[i].length; a++){
System.out.println(payroll[i][a]);
int sum = (payroll[i + a][a]);
}
}
to sum all the values, try this:
int sum = 0;
for(int i = 0; i < payroll.length; i++){
for(int a = 0; a < payroll[i].length; a++){
sum += payroll[i][a];
}
}
System.out.println("the sum is: " + sum);
The code above simply iterates through all the arrays of arrays and adds the value of each element onto the sum variable which then gets printed to the console.

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];
}

Categories