Returning something other than null [duplicate] - java

This question already has answers here:
Comparing arrays in JUnit assertions, concise built-in way?
(8 answers)
Closed 4 years ago.
This is probably a really bad way of writing code but heres a program that calculates the total of each row and print it all in brackets.
public static int[] rowsSums(int[][] array) {
int[][] numArray = {
{3, -1, 4, 0},
{5, 9, -2, 6},
{5, 3, 7, -8}
};
int rowTotal = 0;
int row2Total = 0;
int row3Total = 0;
for (int i = 0; i < numArray[0].length; i++) {
rowTotal += numArray[0][i];
row2Total += numArray[1][i];
row3Total += numArray[2][i];
}
System.out.println("(" + rowTotal + "," + row2Total + "," + row3Total + ")");
return null;
}
The output without JUnit is:
(6,18,7)
I am in the process of testing this with JUnit and my code for this:
#Test
public void rowsSums() {
int [] i = new int [] {6, 18, 7};
assertEquals(i, Exercise2.rowsSums(numArray));
}
Yes, I know my output is not supposed to be null because JUnit hates it. What other variable can I return without making JUnit fail or spit an error?
I have to keep these as it is
public static int[] rowsSums(int[][] array) {
int[][] numArray = {
UPDATE: No matter what I try, JUnit always comes up with this error PrntScrn of Error

To return the int[] containing the sums, you'd do
return new int[] { rowTotal, row2Total, row3Total };
That's something you can assert as well then
assertArrayEquals(i, Exercise2.rowsSums(numArray));
Note that it is good practice to separate calculation and output, ie you should move the System.out.println to another function accepting the returned array as a parameter.

If your method is designed to just print a message and not return anything, you should declare its return type to be void.
public static void rowsSums(int[][] array) { ...
Then just remove the return statement.
However, based on your test case, it looks like you want to return an array containing the values that you calculated. Instead of having three internal variables to hold totals (rowTotal, row2Total, and row3Total), those variables could be combined into one array where the totals are stored, then returned.

I think that your method should return the computation performed and not only print a message otherwise you would not have a clear way to test your method.
Besides method names should be verbs/actions and not common names.
So sum() would be clearer.
You could return the sum array of each row in your method and assert the result in your unit test :
public static int[] sum(int[][] array) {
...
return new int[] {rowTotal, row2Total, row3Total};
}
And in your test :
int[] sumExpected = ...
Assert.assertArrayEquals(sumExpected, Exercise2.sum(numArray));

If you will return array as a result you will be able to use it in your jUnit test and compare expected result with actual.
System.out.println("(" + rowTotal + "," + row2Total + "," + row3Total + ")");
int [] result = new int[3];
result[0] = rowTotal;
result[1] = row2Total;
result[2] = row3Total;
return result;

Why do you pass int[][] array to the method, but literally never do anything with it at all?... I'm going to assume you want to use that array structure you passed in order to count each of it's arrays (rows). You also should never mix output with functions. You should return the String, then print it in your main method. As #bill-the-Lizard said, you want to have an array in which holds the row's values and then you would just return an int[] array which contains the rows' counts. You would then have a for loop in your current one which would input the counts into their corresponding array key.

int[][] numArray = {
{3, -1, 4, 0},
{5, 9, -2, 6},
{5, 3, 7, -8}
};
public static int[] rowsSums(int[][] array) {
int[] sum = new int[array.length];
for (int i=0;i<sum.length; i++)
sum[i] = 0;
for (int i = 0; i < sum.length; i++) {
for(int j=0; j< array[i].length; j++)
sum[i] += array[i][j];
}
return sum;
}
int[] result = rowsSums(numArray);

Related

Error when testing with JUnit using assertArrayEquals

When testing this bit of code:
public static int maxRowAbsSum(int[][] array) {
int[][] maxRowValue = {
{3, -1, 4, 0},
{5, 9, -2, 6},
{5, 3, 7, -8}
};
int maxRow = 0;
int indexofMaxRow = 0;
for (int row = 0; row < maxRowValue.length; row++) {
int totalOfRow = 0;
for (int column = 0; column < maxRowValue[row].length; column++){
if (maxRowValue[row][column] > 0) {
totalOfRow += maxRowValue[row][column];
} else {
totalOfRow -= maxRowValue[row][column];
}
}
if (totalOfRow > maxRow) {
maxRow = totalOfRow;
indexofMaxRow = row;
}
}
System.out.println("Row " + indexofMaxRow + " has the sum of " + maxRow);
return indexofMaxRow;
}
using this JUnit code:
#Test
public void maxRowAbsSum() {
int [] i = new int [] {};
assertArrayEquals(i, Exercise2.maxRowAbsSum(numArray));
}
This underlines assertArrayEquals in red saying:
The method assertArrayEquals(int[], int[]) in the type Assert is not applicable for the arguments (int[], int)
Am I writing this the wrong way? How do I test this with JUnit so it has no errors or faliures?
i is an int array while Exercise2.maxRowAbsSum(numArray) returns int.
Comparing them isn't possible and hence the error.
You are trying to compare an array of int (int[]) with a single int returned from maxRowAbsSum() method. That's not going to work, it's comparing apples to oranges and JUnit guards you against this with it's method signatures.
You should write your test to match the maxRowAbsSum() method return type e.g.:
#Test
public void shouldCalculateMaxRowAbsSum() {
int expected = 3; // example value, change to match your test scenario
assertEquals(expected, Exercise2.maxRowAbsSum(numArray));
}
I fixed my code but still used Karol's example:
Instead of return indexOfMaxRow which just returned the index of the row that had the max value, I changed this to return maxRow this returned 23 instead of the 2 that JUnit was expecting.

Java : I want to change an integer array into a mathematical number [duplicate]

This question already has answers here:
Make individual array values to single number in Python [closed]
(3 answers)
Closed 6 years ago.
Here is my array, it consists of array of integers. Actually, these are the key of my HashMap which consists of some sentences or say "STRING" of a complete paragraph as a key value pair. Now I wanted to join those sentences from taking the key from the integer array one after another in given order.
int[] arr = {3, 2, 0, 5, 3};
HashMap<Integer, String> h = new HashMap<Integer, String>() {{
put(0,"This is my third sentence.");
put(3,"This is my first sentence.");
put(5,"This is my forth sentence.");
put(2,"This is my second sentence.");
}};
The final output should be all the sentences combined as mentioned order and outout should be like a paragraph as :
This is my first sentence.This is my second sentence.This is my third sentence.
This is my forth sentence.This is my first sentence.
Instead of converting the value to a character type you can perform math. For each digit in the array, the corresponding power of 10 is the array length (minus one) minus the index (because Java arrays use 0 based indexing and the last digit corresponds to 100). Something like,
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i] * Math.pow(10, arr.length - i - 1);
}
System.out.println(result);
Output is (as expected)
32053
Optimization
It's possible to optimize the code further by keeping the current power of ten and dividing 10 while iterating each digit. This would also allow the use of a for-each loop like
int[] arr = { 3, 2, 0, 5, 3 };
int result = 0;
int pow = (int) Math.pow(10, arr.length - 1);
for (int digit : arr) {
result += digit * pow;
pow /= 10;
}
System.out.println(result);
Alternatively, iterate the digits from right to left and multiply pow by 10 on each iteration. That might look something like,
int result = 0;
int pow = 1;
for (int i = arr.length - 1; i >= 0; i--) {
result += arr[i] * pow;
pow *= 10;
}
And the above might also be written like
int result = 0;
for (int i = arr.length - 1, pow = 1; i >= 0; i--, pow *= 10) {
result += arr[i] * pow;
}
int number = Integer.parseInt(Arrays.stream(arr).mapToObj(String::valueOf).collect(Collectors.joining()));
Yet another way:
int[] arr = {3, 2, 0, 5, 3};
int i = Integer.parseInt(Arrays.toString(arr).replaceAll("[\\[,\\] ]", ""));
System.out.println(i); // prints 32053
Though fairly simple, you should have tried yourself.
Still providing a solution, just debug and understand it.
Working Code
public static void main(String[] args) throws Exception {
int[] arr = {3, 2, 0, 5, 3};
StringBuilder numberStr = new StringBuilder();
for (int item : arr) {
numberStr.append(item);
}
int finalInt = Integer.parseInt(numberStr.toString());
System.out.println(finalInt);
}
Output
32053
First convert the array into string by appending elements one by one and the convert string into integer. Try this code:
public class NewClass63 {
public static void main(String args[]){
int[] arr = {3, 2, 0, 5, 3};
StringBuffer s = new StringBuffer();
for(int i=0;i<arr.length;i++){
s.append(arr[i]);
}
int x = Integer.parseInt(s.toString());
System.out.println(x);
}
}
int[] array = {3,2,0,5,3};
String x = "";
for(int i = 0;i<=array.length-1;i++){
x = x + String.valueOf(array[i]);
}
System.out.println(Integer.parseInt(x));
use a loop:
int[] arr = { 3, 2, 0, 5, 3 };
String itotal = "";
for (int i = 0; i < arr.length; i++)
{
itotal=itotal + String.valueOf(arr[i]);
}
int a = Integer.parseInt(itotal);
There exist various ways.
If I am right, hidden assumption is that the higher element of integer array matches with higher digit of result integer.
int[] arr = {3, 2, 0, 5, 3};
int result = 0;
int power = (int) Math.pow(10, arr.length-1);
for(int element : arr){
result += element * power;
power /= 10;
}
Easiest solution answer is this.
Assume, each alphabet in the example is a single digit.
Empty Array {} : Expected value = 0
{a}: Expected value = a
{a,b}: Expected value = 10*a + b
{a,b,c}: Expected value = 10 * (10*a + b) + c
Code: Test this is online java compiler IDE
public class ConvertDigitArrayToNumber {
public static void main(String[] args) {
int[] arr = {3, 2, 0, 5, 3};
int value = 0;
for (int i = 0; i < arr.length; i++) {
value = (10*value) + arr[i];
}
System.out.println(value);
}
}
This is actually simpler and better solution than the other ones.
Only simple multiplication and addition (No powers).
No String conversions

Function in java outputs different results when called multiple times

I have a function called tournamentTreeKSelection which finds the K-th largest element in an array. The function takes three parameters, the array, the same array again and the value of K. The purpose of sending two copies of the array is so that during recursive calls, I can modify one copy of the array and still keep the original array I sent in during that call. Here is the code:
import java.util.ArrayList;
import java.util.Arrays;
public class TournamentTree {
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int[] toArray(ArrayList<Integer> list) {
int[] arr = new int[list.size()];
for(int i = 0; i < arr.length; ++i)
arr[i] = list.get(i);
return arr;
}
public static ArrayList<Integer> toList(int[] arr) {
ArrayList<Integer> list = new ArrayList<>();
for(int i : arr)
list.add(i);
return list;
}
public static int tournamentKSelection(int[] data, int[] data_copy, int k) {
ArrayList<Integer> winners = new ArrayList<>();
for(int i = 0; i < data.length; i += 2) {
winners.add(max(data[i], data[i + 1]));
}
if(k > 1 && winners.size() == 1) {
for(int i = 0; i < data_copy.length; i++)
if(data_copy[i] == winners.get(0))
data_copy[i] = -1;
return tournamentKSelection(data_copy, data_copy, --k);
}
if(winners.size() % 2 == 1 && winners.size() != 1) winners.add(-1);
if(winners.size() == 1) return winners.get(0);
return tournamentKSelection(toArray(winners), data_copy, k);
}
}
Now I am going to test it :
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,1));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,2));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
This produces the following results:
500 // ok this is the first largest number
10 // ok this is the second largest number
8 // this is the fourth largest number, not the third
Now let me make the call to System.out.println(TournamentTree.tournamentKSelection(arr,arr,3)); alone without the call to k = 1 and k = 2
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
Now this produces the correct result, which is 9. What's going on ? Individually, the result is correct but when I make previous calls to the same function first the subsequent results are wrong.
The only explanation I can think of at the moment is that something in my TournamentTree class is static that shouldn't be.
Any insight ?
I think you should call your function in this way:
System.out.println(TournamentTree.tournamentKSelection(arr.clone(), arr.clone(), 1));
And I recommend also interesting thread about arrays and passing them to function:
Are arrays passed by value or passed by reference in Java?
In the call TournamentTree.tournamentKSelection(arr,arr,3), you are passing in the same array for both args, so even though you are not changing the array through the second argument, you are changing it by the first. Java uses pass by reference, not pass by value. To maintain the original, you have to make a copy and pass in each, like:
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
int[] arr_copy = java.util.Arrays.copyOf(arr, arr.length);
System.out.println(TournamentTree.tournamentKSelection(arr,arr_copy,3));
}

Java program output strange result

I am having an output problem with my java code.
I am trying to implement this multiply matrix method and it compiles just fine. The only problem is my output. I seem to be getting the following:
---- Test Multiply Matrix ----
[[D#7f31245a
Should return C={{ 3, 2},{ 1, 1}}
Can someone please help me understand where I am going wrong here. Thanks!
Here is my source code:
public class Recommendation
{
public static double[][] multiplyMatrix(double[][] A, double[][] B)
{
int aRows = A.length;
int bRows = B.length;
int aColumns = A[0].length;
int bColumns = B[0].length;
if((aColumns != bRows))
{
return null;
}
else
{
double[][] C = new double[aRows][bColumns];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
C[i][j] = 0;
}
}
for (int i = 0; i < aRows; i++)
{
for (int j = 0; j < bColumns; j++)
{
for (int k = 0; k < aColumns; k++)
{
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
}
static double [][] A = {{ 1, 0, 2},
{ 0, 1, 1}};
static double [][] B = {{1, 2},
{ 0, 1},
{ 1, 0}};
public static void main(String[] argss)
{
// TEST multiplyMatrix
System.out.println(" ---- Test Multiply Matrix ---- ");
System.out.println(multiplyMatrix(A,B)); // should return C={{ 3, 2},{ 1, 1}}
System.out.println("Should return C={{ 3, 2},{ 1, 1}}");
System.out.println(" ");
}
}
You might want to use Arrays.toString from java.util.Arrays to print arrays.
Or, if you want your output to be a little more custom, you can iterator over the array.
Note that Arrays.toString alone won't help you, since your array is two dimensional.
It would still print something of the form : [[I#355d56d5, [I#2efd552, [I#4f9dfbff]
Instead, you can do something like this :
double[][] C = multiplyMatrix(A,B);
for (double[] subArray : C) {
System.out.print (Arrays.toString (subArray));
System.out.print (" , ");
}
System.out.println();
Or, you can use Arrays.deepToString(C) which will take care of the hierarchy for you.
#deepToString Returns a string representation of the "deep contents" of the
specified array. If the array contains other arrays as elements, the
string representation contains their contents and so on. This method
is designed for converting multidimensional arrays to strings.
You should use java.util.Arrays.deepToString(array) for multi-dimensional array.Currently you are printing Object reference's String representation.
You can use #replace method to replace[] with {}
//...
public static void main(String[] argss){
// TEST multiplyMatrix
System.out.println(" ---- Test Multiply Matrix ---- ");
double array[][] = multiplyMatrix(A,B);
String finalString = Arrays.deepToString(array)
.replace("[", "{")
.replace("]", "}");
System.out.println(finalString);
}//...
public static double[][] multiplyMatrix(double[][] A, double[][] B).
Here you are returning a double array. which is not a primitive type. So, the default toString() method of array will be used (Which prints classname#hashCode, hence the output). You have to use Arrays.toString() to print the values properly.
[[D#7f31245a means a 2D array of Double's followed by the hashcode of the actual object.
Your multiplyMatrix() method returns exactly this, but the toString() method invoked is that on Object which prints exactly this. You'll need to to use methods on Arrays class to prettyprint arrays.
Cheers,
You can use Arrays#deepToString():
System.out.println(Arrays.deepToString(multiplyMatrix(A,B)));
multiplyMatrix returns an array, which is an object, and in Java since each object has toString() method, the default is displaying the class name representation, then adding # sign and then the hashcode.
In order to better understand what's happening here, see the implementation of Arrays.deepToString.
Note that if you want more control on the output, e.g. filtering some arrays or change the way display them, you can have nested loops.

Checking if Integer is in Array Java does not return expected values

I have looked in many places online and all seem to give me the same solution. So it's obvious that I have made some sort of silly mistake I cannot see. Can someone please point me in the right direction. Thanks a mill.
Here is my code:
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
int[] outcomes = {1, 2, 3, 4, 5, 6};
int count = 0;
for(int y = 1; y<=6; y++){
if(Arrays.asList(outcomes).contains(y)){
count++;
System.out.println("outcomes contains "+ y);
}
}
System.out.println(count);
}
The final output should be 6 but it is 0.
Arrays.asList(int[])
returns a single-element list. The one element is the int[] you have passed in.
If you change the declaration
int[] outcomes
to
Integer[] outcomes
you'll get the expected result.
Two things should be corrected in your code:
Changing int[] to Integer[] (as sugested Marko Topolnik in previous answer)
Moving Arrays.asList befor for loop. Now array is converted to list 6 times.
After this changes code will look as follows:
public static void main(String[] args) {
Integer[] outcomes = {1, 2, 3, 4, 5, 6};
List outcomesList = Arrays.asList(outcomes);
int count = 0;
for(int y = 1; y<=6; y++){
if(outcomesList.contains(y)){
count++;
System.out.println("outcomes contains "+ y);
}
}
System.out.println(count);
}

Categories