multiplying all elements in an array by an outside number? - java

I need to multiple all the values in an array by 3000 which in turn would create a new array that I will use to subtract from another array. I've tried to create a separate method that would do that for me but all I got back in the multiplied array was a bunch of numbers and symbols strangely?
here is the code that I wrote
public static void main(String[] args)
{
int numberOfTaxpayers = Integer.parseInt(JOptionPane.showInputDialog("Enter how many users you would like to calculate taxes for: ");
int[] usernumChild = new int[numberOfTaxPayers];
for (int i = 0; i < usernumChild.length; i++)
{
usernumChild[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter number of children for user "+ (i+1) +": "));
}//this for loop finds out the number of children per user so we can later multiply each input by 3000 to create an array that determine dependency exemption for each user
int[] depndExemp = multiply(usernumChild, 3000);//this was the calling of the multiply method... somewhere here is the error!!
}//end main method
public static int[] multiply(int[] children, int number)
{
int array[] = new int[children.length];
for( int i = 0; i < children.length; i++)
{
children[i] = children[i] * number;
}//end for
return array;
}//this is the method that I was shown in a previous post on how to create return an array in this the dependency exemption array but when I tested this by printing out the dependency array all I received were a jumble of wrong numbers.

In your example you're multiplying your children array but returning your new array. You need to multiply your new array by your children array.
1 public static int[] multiply(int[] children, int number)
2 {
3 int array[] = new int[children.length];
4 for( int i = 0; i < children.length; i++)
5 {
6 array[i] = children[i] * number;
7 }//end for
8 return array;
9 }
The reason you're getting strange symbols is because you are returning uninitialized values. The array itself is allocated at line 3 but at this point each index of the array has not been initialized so we don't really know what values are in there.

Using Java 8 streams it can be as simple as:
public static int[] multiply(int[] children, int number) {
return Arrays.stream(children).map(i -> i*number).toArray();
}

You really don't have to create new array in your method (and you are also returning the old one without any change). So just do
public static int[] multiply(int[] children, int number) {
for(int i = 0; i < children.length; i++) {
children[i] = children[i] * number;
}
return children;
}

You need to Change
children[i] = children[i] * number;
to
array[i] = children[i] * number;

If I understand your question correctly:
children[i] = children[i] * number;
Should be changed to
array[i] = children[i] * number;
Considering you are returning array, not children.

In your second for loop it should be :
for(int i = 0; i < children.length; i++){
array[i] = children[i] * number;
}//end for
Also make sure that all values of children[i] are inferior than ((2^31 - 1)/number) +1

Related

Trying to create a array with the intersection of two arrays but fails at creating array with the proper structure

So, I am trying to create 2 randomly generated arrays,(a, and b, each with 10 unique whole numbers from 0 to 20), and then creating 2 arrays with the info of the last two. One containing the numbers that appear in both a and b, and another with the numbers that are unique to a and to b. The arrays must be listed in a "a -> [1, 2, 3,...]" format. At the moment I only know how to generate the 2 arrays, and am currently at the Intersection part. The problem is, that I can create a array with the correct list of numbers, but it will have the same length of the other two, and the spaces where it shouldn't have anything, it will be filled with 0s when its supposed to create a smaller array with only the right numbers.
package tps.tp1.pack2Arrays;
public class P02ArraysExtractUniqsAndReps {
public static void main(String[] args) {
int nbr = 10;
int min = 0;
int max = 20;
generateArray(nbr, min, max);
System.out.println();
}
public static int[] generateArray(int nbr, int min, int max) {
int[] a = new int[nbr];
int[] b = new int[nbr];
int[] s = new int[nbr];
s[0] = 0;
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * (max - min));
b[i] = (int) (Math.random() * (max - min));
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--;
}
if (b[i] == b[j]) {
i--;
}
}
}
System.out.println("a - > " + Arrays.toString(a));
System.out.println("b - > " + Arrays.toString(b));
for (int k = 0; k < a.length; k++) {
for (int l = 0; l < b.length; l++) {
if (a[k] == b[l]) {
s[l] = b[l];
}else {
}
}
}
System.out.println("(a ∪ (b/(a ∩ b)) - > " + Arrays.toString(s));
return null;
}
public static boolean hasValue(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
}
Is there any way to create the array without the incorrect 0s? (I say incorrect because it is possible to have 0 in both a and b).
Any help/clarification is appreciated.
First, allocate an array large enough to hold the intersection. It needs to be no bigger that the smaller of the source arrays.
When you add a value to the intersection array, always add it starting at the beginning of the array. Use a counter to update the next position. This also allows the value 0 to be a valid value.
Then when finished. use Array.copyOf() to copy only the first part of the array to itself, thus removing the empty (unfilled 0 value) spaces. This works as follow assuming count is the index you have been using to add to the array: Assume count = 3
int[] inter = {1,2,3,0,0,0,0};
inter = Arrays.copyOf(inter, count);
System.out.println(Arrays.toString(inter);
prints
[1,2,3]
Here is an approach using a List
int[] b = {4,3,1,2,5,0,2};
int [] a = {3,5,2,3,7,8,2,0,9,10};
Add one of the arrays to the list.
List<Integer> list = new ArrayList<>();
for(int i : a) {
list.add(i);
}
Allocate the intersection array with count used as the next location. It doesn't matter which array's length you use.
int count = 0;
int [] intersection = new int[a.length];
Now simply iterate thru the other array.
if the list contains the value, add it to the intersection array.
then remove it from the list and increment count. NOTE - The removed value must be converted to an Integer object, otherwise, if a simple int value, it would be interpreted as an index and the value at that index would be removed and not the actual value itself (or an Exception might be thrown).
once finished the intersection array will have the values and probably unseen zeroes at the end.
for(int i = 0; i < b.length; i++) {
int val = b[i];
if (list.contains(val)) {
intersection[count++] = val;
list.remove(Integer.valueOf(val));
}
}
To shorten the array, use the copy method mentioned above.
intersection = Arrays.copyOf(intersection, count);
System.out.println(Arrays.toString(intersection));
prints
[3, 2, 5, 0, 2]
Note that it does not matter which array is which. If you reverse the arrays for a and b above, the same intersection will result, albeit in a different order.
The first thing I notice is that you are declaring your intersection array at the top of the method.
int[] s = new int[nbr];
You are declaring the same amount of space for the array regardless of the amount you actually use.
Method Arrays.toString(int []) will print any uninitialized slots in the array as "0"
There are several different approaches you can take here:
You can delay initializing the array until you have determined the size of the set you are dealing with.
You can transfer your content into another well sized array after figuring out your result set.
You could forego using Array.toString, and build the string up yourself.

How to find the largest number in the array

I have an array of grades(g) which is an int[] and I'm trying to find the largest grade in that array. I have tried this:
public static String highestGradeName(int[] g, String[] n) {
String highStudent;
int highest = g[0];
for (int i=1; i < g.length; i++) {
if (highest < g[i]) {
highStudent = n[i+1];
return (highStudent);
}
}
return null;
}
I have another array which is a String array and contains the names of the students, I have the return null there because it said it needed a return statement however I didn't plan on it ever being null. What's causing it to return null instead of highstudent?
I've used the exact code to find the lowest grade and it works fine the only thing I did to this one was change the if statement from highest > g[i] to highest < g[i].
Returning from inside the loop is wrong, as you can always have an even larger number later on in the array. You should keep the index of the highest grade and just return the corresponding name at the end:
public static String highestGradeName(int[] g, String[] n) {
int highest = 0;
for (int i = 1; i < g.length; i++) {
if (g[highest] < g[i]) {
highest = i;
}
}
return n[highest];
}
According to your logic let's break things.
Raw Test Case:
Take {0,1,2} as an integer arrays.
Take {"arya", "jon", "tyrion"} as an string arrays.
highest = 0; // according to your code.
For int i = 1, i < 3; i++
0 < 1
highstudent = 2 // tyrion
// returns tyrion
The reason why you are getting null is your integer at 0 index should be greater or equal to the index at 1.
Now, when you are using a type String in your method. You should return a string and that's what your editor said to have something return. You should use return out of the loop because you need to find the highest student which is only possible after looping all the list.
You can try this:
public static String highestGradeName(int[] g, String[] n) {
int max = 0;
int index = 0;
for (int i = 0; i < g.length; i++) {
if (max < g[i]) {
max = g[i];
index = i;
}
}
return n[index];
}
PS: Imporve code according to mureinik answer, I have one more variable to help you understand easily.

2D Array with variable internal array length JAVA

Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Covert 2D array to 1D array storing the 2D array position (col, row) and the value in a 1D array

I have managed to convert it to output the values from the 2D array, but have no idea how to get the position.
Here is my code:
public static int[] convert(int [][]twodarray)
{
int[] onedarray = new int[twodarray.length * twodarray.length];
for(int i = 0; i < twodarray.length; i ++)
{
for(int s = 0; s < twodarray.length; s ++)
{
onedarray[(i * twodarray.length) + s] = twodarray[i][s];
}
}
return onedarray;
}
public static int [] printonedarray(int [] onedarray)
{
System.out.print("onedarray: ");
for(int i = 0; i < onedarray.length; i++)
{
System.out.print(onedarray[i] + "\t");
}
System.out.println();
return onedarray;
}
assuming that your 2-d array is not a jagged array, than the original cordinates for A[i] should be A[i/x][i%x] where x is the original length of the least significant column your 2/d array
Okay, I am not really sure if I get you correclty. But I understand it this way:
You have a 2 dim. array and want to convert it to a 1 dim. array.
Therefore you want to ready the first coloumn and the first line.
Then you want to add this value at the forst position of the 1 dim. array.
Then you read the next row and want to add this value and so on.
If I am right I suggest an arrayList for your 1 dim array. Because you don't know how deep the coloumns are. And ArrayLists are dynamic. You can simply add an element and don't need to give a position.
Your code suggestion was pretty good and I just converted it to an ArrayList.
import java.util.ArrayList;
public class test
{
public static ArrayList<Integer> convert(int [][]twodarray)
{
ArrayList<Integer> onedarray = new ArrayList<Integer> ();
for(int i = 0; i < twodarray.length; i ++)
{
for(int s = 0; s < twodarray[i].length; s ++)
{
onedarray.add(twodarray[i][s]);
}
}
return onedarray;
}
public static ArrayList<Integer> printonedarray(ArrayList<Integer> onedarray)
{
System.out.print("onedarray: ");
for(int i = 0; i < onedarray.size(); i++)
{
System.out.print(onedarray.get(i) + "\t");
}
System.out.println();
return onedarray;
}
}
If I missed your question I am sorry for a "wrong" answer.
I hope it will help you!

Multiplying 2d array in java

I have declared an array that i would like to multiply the value of the first column by value of the second column of each row and create a grand sum of these products. I have tried the code listing below, what am i missing
public class Arrays {
public static void(String[] args) {
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int sum = 0;
for (int i = 0; i < array_x.length; i++) {
for (int j = 0; j < array_x.length; j++) {
array_x[i][j] = i * j;
System.out.println("\n" + array_x[i][j])
}
}
}
}
The output should be something like
9*8=72
2*17=34 etc then sum the whole results as 72+34+....
The code you wrote had several issues, including the fact that it would not compile because you had a different number of open and closed brackets, you didn't specify the function name (which I assumed to be main) and there was a ; missing. However the biggest issue was a logical one: you only need a single for to do what you want to do. You know that the indices of the second dimension of the array are going to be 0 and 1, because as you said the array has only two columns. Also, you need to accumulate the products into sum, instead you initialized sum to 0 and never updated it. Finally, the instruction array_x[i][j] = i * j multiplies the indices instead of the values, so the result is not what you expect, and this result is put into array_x, which is the wrong place because you really don't need to alter the input array.
class Arrays{
public static void main(String[] args){
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int sum=0;
for(int i=0;i<array_x.length;i++) {
int prod = array_x[i][0] * array_x[i][1];
System.out.println("\n"+prod);
sum += prod;
}
System.out.println("Final: " + sum);
}
}
The code you originally wrote is actually what you need to build a multiplication table, but in that case you need an array with an equal number of rows and columns.
public class Arrays {
public static void main (String[] args) {
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int multiply[] = new int[7];
for (int i = 0; i < array_x.length; i++) {
multiply[i] = array_x[i][0] * array_x[i][1];
}
int sum = 0;
for(int i = 0; i < multiply.length; i++)
{
System.out.println(array_x[i][0] + "*" + array_x[i][1] + "=" + multiply[i]);
sum += multiply[i];
}
System.out.println("Sum:" + sum);
}
}

Categories