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];
}
Related
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(" ");
}
This is the output i need (
Input Array: 1 2 3 4 5 6 7
Random Output: 7 2 3 6 1 5 4)
this is what i get
Input size of the Array
5
Input Value
1
Input Value
2
Input Value
3
Input Value
4
Input Value
5
Random Output: 2
Random Output: 0
Random Output: 0
Random Output: 0
Random Output: 0
The problem is with line 23 and im not sure how to fix it
import java.util.Random;
import java.util.Scanner;
public class problem_2 {
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value " +(i+1));
a[i] = m.nextInt();
}
int cell = 0;
int x = r.nextInt(size);
int value = a[x];
while(cell<size) {
for(int i =0; i<= size;i++) {
if (b[i]==value) {
cell++;
}
if(cell==0) {
b[cell] = value;
cell++;
}
System.out.println("Random Output: "+b[i]);
}
}
}
}
The problem is your code is going one too many indexes in the following for loop:
for(int i =0; i<= size;i++)
That's because you have to remember an array with say 5 elements has indexes 0-4. So while the size is the number of elements in the array the largest index is always (the number of elements) - 1.
So you should write the for loop like so:
for(int i = 0; i < size;i++)
Even then your code doesn't quite randomize correctly. The easiest way to randomize an array would be to swap out each element with another random element, like this:
//Randomize the array
for(int i = 0; i < size;i++) {
//lets get a random index in the array
int randIndex = (int)(Math.random()*size);
//then we will store the index we are swapping because its going to be overwritten
int temp = a[i];
//set our index equal to the random one
a[i] = a[randIndex];
//put our index's original value into the random index, so its not lost
a[randIndex] = temp;
}
thanks everyone for the help but i didnt learn any of the things in the others so
i found a easier way to do it
import java.util.Random;
import java.util.Scanner;
public class random{
public static void main(String args[]){
Random r = new Random();
Scanner m = new Scanner(System.in);
System.out.println("Input size of the Array");
int size = m.nextInt();
int a[] = new int[size];
int b[] = new int[size];
for(int i = 0;i<a.length;i++) {
System.out.println("Input Value ");
a[i] = m.nextInt();
}
int cell = 0;
while(cell<size) {
int n = r.nextInt(size);
int value = a[n];
int count = 0;
for(int i =0; i< size;i++) {
if (b[i]== value) {
count++;
}
}
if(count==0) {
b[cell] = value;
cell++;
}
}
System.out.println ("\n");
System.out.println("Input Array: ");
for (int i = 0; i<size; i++){
System.out.print(a[i] + " ");
}
System.out.println ("\n");
System.out.println("Random Output: ");
for (int i = 0; i<size; i++){
System.out.print(b[i] + " ");
}
}
}
I am trying to let the user input the number of elements arrA and arrB should have and also making the user choose the int number they want for each corresponding element in both, arrA and arrB. Then, creating the third arrC with the sum of the corresponding elements in arrA and arrB and then printing arrA, arrB and arrC.
The output should look like this:
Input the length: 5
Enter a value for first array, position 0: 1
Enter a value for first array, position 1: 6
Enter a value for first array, position 2: 13
Enter a value for first array, position 3: -3
Enter a value for first array, position 4: 8
Enter a value for second array, position 0: 9
Enter a value for second array, position 1: -4
Enter a value for second array, position 2: 1
Enter a value for second array, position 3: 65
Enter a value for second array, position 4: 18
first: 1 6 13 -3 8
second: 9 -4 1 65 18
result: 10 2 14 62 26
This is the code I have written so far and I need help as to how would i use scanner to let the user choose the input length of arrA and arrB and the elements in arrA and arrB. This is what the code looks like so far :-
class ArrayArithmetic
{
public static void main ( String[] args )
{
int[] arrA = { 11, -27, 89, 17};
int[] arrB = {-3, 24, -9, -16};
int[] sum = { 0, 0, 0, 0};
for(int i = 0; i < arrA.length - 1; i++)
{
for(int j = 0; i < arrB.length - 1; i++)
{
sum[i] = arrA[i] + arrB[i];
}
}
System.out.println("sum: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );
}
}
Lets suppose you have only 2 arrays to make it easy and don't nest loops, when you understand this pieces of code you can wrap all the method with a new loop and create infinite arrays to sum to result if you want... but you have to understand the basics first:
Create a Scanner and ask user for the lenght of the arrays:
Scanner sc = new Scanner(System.in);
// ask user!
System.out.println("Input the length:");
int arrayLength = in.nextInt();
Create the arrays with given lenght
int[] fistArray = new int[arrayLength];
int[] secondArray = new int[arrayLength];
int[] totals = new int[arrayLength];
Fill fist array iterating positions from 0 to number entered by user:
for (int i = 0; i < arrayLength; i ++) {
System.out.println("Enter a value for first array, position "+ i);
try {
firstArray[i] = Integer.parseInt(sc.nextLine());
} catch (Exception e) {
System.out.println("Not a valid number!!!);
i --;
}
}
Fill second array iterating positions from 0 to number entered by user and get the sum of each pos:
for (int i = 0; i < in.nextInt(); i ++) {
System.out.println("Enter a value for second array, position "+ i);
try {
secondArray[i] = Integer.parseInt(sc.nextLine());
totals[i] = fistArray[i] + secondArray[i];
} catch (Exception e) {
System.out.println("Not a valid number!!!);
i --;
}
}
And print the results:
System.out.println(Arrays.toString(firstArray));
System.out.println(Arrays.toString(secondArray));
System.out.println(Arrays.toString(totalsArray));
Finally, don't forget to close your Scanner to avoid memory leaks as pointed drgPP so:
sc.close();
The following code should do as you wanted:
import java.util.*;
class ArrayArithmetic
{
public static void main ( String[] args )
{
Scanner in = new Scanner(System.in);
System.out.print("Input the length ");
int len = in.nextInt();
int[] arrA = new int[len];
int[] arrB = new int[len];
int[] sum = new int[len];
for (int i = 0; i < len; i++){
System.out.print("Enter a value for first array, position " + i + ": ");
arrA[i] = in.nextInt();
}
for (int i = 0; i < len; i++){
System.out.print("Enter a value for second array, position " + i + ": ");
arrB[i] = in.nextInt();
}
for(int i = 0; i < arrA.length; i++)
{
for(int j = 0; i < arrB.length; i++)
{
sum[i] = arrA[i] + arrB[i];
}
}
System.out.println("sum: " + sum[0]+"," + sum[1] + "," + sum[2] + "," + sum[3] );
} }
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Length of arrays: ");
try {
//Initializing length of array
int length = sc.nextInt();
//Constructing our arrays based on length
int[] arrA = new int[length];
int[] arrB = new int[length];
int[] arrSum = new int[length];
//Populating our array A via a loop
for (int i=0; i<arrA.length; i++) {
System.out.println("Values for arrA at index: "+i);
int value = sc.nextInt();
arrA[i]=value;
}
//Populating our array B via a loop
for (int i=0; i<arrB.length; i++) {
System.out.println("Values for arrB at index: "+i);
int value = sc.nextInt();
arrB[i]=value;
}
//Call the method to calcualte our sum which will be in sum array
arrSum = makeSum(arrA, arrB, length);
System.out.println(Arrays.toString(arrSum));
} catch (Exception e) {
e.printStackTrace();
} finally {
sc.close();
}
}
// Method to calculate our Sum Array based on the length and the Array A and B
public static int[] makeSum (int[] arrA, int[] arrB, int length) {
int[] arrSum = new int[length];
for (int i=0; i<arrA.length; i++) {
for (int j=0; j<arrB.length; j++) {
arrSum[j]=arrA[i]+arrB[j];
}
}
return arrSum;
}
Perhaps this is your question:
Scanner scan = new Scanner(System.in);
System.out.println("Enter size: ");
int size =scan.nextInt();
Integer[] arrA = new Integer[size];
ArrayList<Integer> arrB = new ArrayList<Integer>(size);
I wanted to create a temporary array to store the input by the user and sort it to get the m smallest elements and refer to the original index of the originalArray and then print the index of the m smallest elements but when I run my code, all I get is -1. My elements should not be out of bounds of the original array as it is taken from originalArray. Why am I getting -1?
import java.util.*;
public class MinimumSelection
{
public static void main(String[] args)
{
//Array and variable declarations
int[] originalArray;
int[] tempArray;
int tempValue;
int lowestValue;
int arrayLength;
String elementValue;
//Prompt the user for random numbers as an array input
System.out.println("Please Enter your array length");
arrayLength = Integer.parseInt(new Scanner(System.in).nextLine());
//Input feeds as the length of the array as entered by user
originalArray = new int[arrayLength];
//Storing the input value in temporary array which will be used to sort
tempArray = new int[arrayLength];
//prompt user to enter elements of the orignial array
for (int element = 0; element < originalArray.length; element++)
{
System.out.printf("\n Enter array elements %1$s: " + "\r\n", element + 1);
elementValue = new Scanner(System.in).nextLine();
originalArray[element] = Integer.parseInt(elementValue);
}
System.arraycopy(originalArray, 0, tempArray, 0, originalArray.length);
//Sorting the original array
for (int write = 0; write < tempArray.length; write++)
{
for (int sort = 0; sort < tempArray.length - 1 - write; sort++)
{
if (tempArray[sort] > tempArray[sort + 1])
{
tempValue = tempArray[sort + 1];
tempArray[sort + 1] = tempArray[sort];
tempArray[sort] = tempValue;
}
}
}
//promoting user to enter no. of smallest elements they want this program to display
System.out.println("Please Enter number of smallest element");
lowestValue = Integer.parseInt(new Scanner(System.in).nextLine());
//display output
System.out.println("Result :");
for (int loop = 0; loop < lowestValue; loop++)
{
int x = tempArray[loop];
int y = Arrays.asList(originalArray).indexOf(x);
// Arrays.asList(array).indexOf(4);
System.out.println((new Integer(y)).toString());
}
new Scanner(System.in).nextLine();
}
}
Create a TreeMap where the key is the element and the value is its index in the original array. Then you iterate through the entries of this map and break out of the loop after the first m steps.
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();