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);
Related
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] );
I have an assignment that requires that I create two arrays (with user defined length) full of random numbers between 1-100, then merge the two arrays without duplicates in alternating order. I just need help merging the two without any repeating numbers. Can anyone help? Thanks!
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int f=0;
int j=0;
int k=0;
//getting first array length and making array1 and array2 that length
while (f==0){
System.out.println("Enter an array length (must be 10 or greater):");
int length = scan.nextInt();
if (length < 10){
f=0;
}
else{
f=1;
}
if (f==1){
int [] array1 = new int[length];
int [] array2 = new int[length];
int [] array3 = new int[length*2];
System.out.print("First Array: ");
//creating random integers between 1 and 100 inclusive to fill array1
for (int i=0; i<=length-1; i++){
int x = (int)(Math.random()*100)+1;
array1[i] = x;
System.out.print(x+" ");
}
//creating random integers between 1 and 100 inclusive to fill array2
System.out.print("\nSecond Array: ");
for (int i=0; i<=length-1; i++){
int y = (int)(Math.random()*100)+1;
System.out.print(y+" ");
array2[i] = y;
}
//combining both arrays
System.out.print("\nMerged Array: ");
for (int i=0; i<=length*2-1; i++){
if ((i==0) || (i%2==0)){
array3[i] = array1[j];
j++;
}
else{
array3[i] = array2[k];
k++;
}
System.out.print(array3[i]+" ");
}
}
}
}
}
First, let's extract your method to fill arrays.
static int[] fillRandomArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = (int) (Math.random() * 100) + 1;
System.out.print(arr[i] + " ");
}
System.out.println();
return arr;
}
Now you can simplify your code to use that method, and your merge is very close; you don't need j or k in each case you are indexing by half of i (the cases being even or odd). Like,
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Enter an array length (must be 10 or greater):");
int length = scan.nextInt();
if (length >= 10) {
System.out.print("First Array: ");
// creating random integers between 1 and 100 inclusive to fill array1
int[] array1 = fillRandomArray(length);
// creating random integers between 1 and 100 inclusive to fill array2
System.out.print("\nSecond Array: ");
int[] array2 = fillRandomArray(length);
// combining both arrays
System.out.print("\nMerged Array: ");
int[] array3 = new int[array1.length + array2.length];
for (int i = 0; i < array3.length; i++) {
if (i % 2 == 0) {
array3[i] = array1[i / 2];
} else {
array3[i] = array2[i / 2];
}
System.out.print(array3[i] + " ");
}
System.out.println();
}
}
If you actually need to eliminate duplicates between array1 and array2 while you merge, then you can't assume that the output array will be double the input length. I would use a Set. Like,
// combining both arrays
System.out.print("\nMerged Array: ");
Set<Integer> set = new LinkedHashSet<>();
for (int i = 0; i < array1.length + array2.length; i++) {
if (i % 2 == 0) {
if (set.add(array1[i / 2])) {
System.out.print(array1[i / 2] + " ");
}
} else {
if (set.add(array2[i / 2])) {
System.out.print(array2[i] + " ");
}
}
}
// If you actually need an int[]
int[] array3 = set.stream().mapToInt(Integer::intValue).toArray();
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] + " ");
}
}
}
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];
}
The problem:
a program that updates a list of students’ grades after the end of drop period. The program should reads from the user number of students who dropped and their indexes, and then the program should copies the remaining student’s grades to new array. In addition, the program should display both the original and the updated list. [Hint: the new array must have suitable length equivalents to number of remaining students]
my code:
public class Q5{
static Scanner scan = new Scanner (System.in);
public static void main (String args[]){
double [] list={1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};
System.out.println("enter number of students who dropped:");
int num=scan.nextInt();
double [] list2 = new double [num];
System.out.println("Enter index Of the student who dropped ");
for (int j=1 ; j<=num ; j++)
{
System.out.println("student" + j + ":");
int index=scan.nextInt();
list[index]=0;
}
int j=0;
for(int i=0; i<list.length ; i++)
if (list[i]!=0)
{
list2[j]=list[i];
j++;
}
System.out.print("The original list : " );
for(int i=0; i<list.length ; i++)
System.out.print(list[i] + " " );
System.out.print("remaining students " );
for(int i=0; i<list2.length ; i++)
System.out.print(list2[i] + " " );
}
}
what is the problem ? it is not working !!!
in Line 16 it says :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Q5.main(Q5.java:23)
how I can correct this
That's because of the size of your list2.
You shouldn't set its size to num, but rather to the size of the original list. Because the list2 is going to contain just as many elements as the original list. You need the num only to fetch that many inputs from the user and assign those indexes with the value 0.
double[] list2 = new double[list.length]; // This should be the size of your list2
If you don't need to keep the original size, then you need to subtract the num from the original size, as suggested by #Joetjah.
double[] list2 = new double[list.length - num]; // This should be the size of your list2
Pseudo-code:
You start of with 10 students. Say you want to drop 2 students. That means you set the list2 size to 2.
Next thing you do, is trying to add all the students (10) from list to list2. But, list2 is too small for this. Thus you get your Exception.
What you want, is this:
double [] list2 = new double [list.length - num];
Guess that problem with predefined array 'list'.
Step 1: Created the list with one of the initializing ways. Here the size is fixed.
Step 2: Took input from user : lets assume it is 11.
list doesn't need to contain the size given as input.
You initialize list2 with wrong size.
You get from the user number of dropped students and then try to put in list2 all the remaining students.
double [] list2 = new double [list.length - num];
Your code will fail if the value entered by user is out of bounds for the array :
int index=scan.nextInt();
list[index]=0; // This may fail. Value entered by the user may exceed the array length
Its working fine
import java.util.Scanner;
public class Q5 {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("enter number of students who dropped:");
int num = scan.nextInt();
double[] list2 = new double[num - 1]; // should be num-1
System.out.println("Enter index Of the student who dropped ");
for (int j = 0; j < num; j++) {
System.out.println("student" + j + ":");
int index = scan.nextInt();
list[index] = 0;
}
int j = 0;
for (int i = 0; i < num; i++) {
if (list[i] != 0) {
list2[j] = list[i];
j++;
}
}
System.out.print("The original list : ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("remaining students ");
for (int i = 0; i < list2.length; i++) {
System.out.print(list2[i] + " ");
}
}
}
output is
enter number of students who dropped:
2
Enter index Of the student who dropped
student0:
1
student1:
2
The original list : 1.0 0.0 0.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 remaining students 1.0
This will remove the exception you got. From next time you don't use static values.
Edit:
It is not a good practice to assign values to any variable by yourself. As the array is having size of 10. If user enters more than 10 students dropped then it will cause a problem.
import java.util.*;
public class Q5 {
static Scanner scan = new Scanner(System.in);
public static void main(String args[]) {
double[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("enter number of students who dropped:");
int num = scan.nextInt();
double[] list2 = new double[list.length-num]; // should be num-1
System.out.println("Enter index Of the student who dropped ");
for (int j = 0; j < num; j++) {
System.out.println("student" + j + ":");
int index = scan.nextInt();
list[index] = 0;
}
int j = 0;
for (int i = 0; i < list.length; i++) {
System.err.println(""+list[i]);
if (list[i] > 0) {
list2[j] = list[i];
j++;
}
}
System.out.print("The original list : ");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("remaining students ");
for (int i = 0; i < list2.length; i++) {
System.out.print(list2[i] + " ");
}
}
}