I have no problem calling methods that require String or int inputs. For example:
return stringMethod("Hello World");
return intMethod(1,2,3);
but I'm having an issue with the syntax when calling a method which requires array of ints for the input. The syntax I use to call the method countEvens in the code below is not working.
public class _01_countEvens{
public static void main(String[] args){
return countEvens({2,4,6,7});
}
}
public int countEvens(int[] nums){
int result = 0;
for(int x = 0; x < nums.length; x++){
if(nums[x] % 2 == 0) result++;
}
return result;
}
}
This syntax
{2,4,6,7}
is the array creation syntax and can only be used in array creation expressions
new int[]{2,4,6,7}
Read the official Java tutorial on Arrays here.
Either change your method header to:
public int countEvents(int... nums)
And remove the { and } in the call to countEvents,
Or pass: new int[]{2, 4, 6, 7} as an argument.
Array:
int[] a = {0,1,2,3,4,5};
Double Array:
int[][] a2 = {
{0,1,2}
{3,4,5}
};
From there on, just add arrays inside each array. You shouldn't have to make that many dimensions though.
Related
I'm currently trying to find all the multiple values of three in an array. I know hot to do it without using a method, but when I'm trying to invoke the method and retrieve the returned array, it gives me errors and won't work.
public class Scratchpad extends ConsoleProgram
{
public void run()
{
int[] test = {4, 7, 9, 7, 12};
findMultipleOfThree testArr = new findMultipleOfThree[int[] test];
System.out.println(testArr);
}
// Copy and paste your Unit Test method here
public int findMultipleOfThree(int[] arr)
{
int length = arr.length;
int[] result = new int[length];
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 3 == 0)
{
result[i] = arr[I];
}
}
return result;
}
}
There are a few problems in your code. I think that in your second instruction of the run method, you were attempting to invoke the findMultipleOfThree method you defined below.
To invoke a method, you simply need to type its name and pass the parameters it's expecting. In your case, the test array to find the elements divisible by 3. Plus, you also need to declare a second array result in order to store the returned array from your method with only the elements divisible by 3.
Ultimately, in your findMultipleOfThree method there was a small typo where you referred to the i variable as I. Java is case-sensitive, so it distinguishes between lower-case and upper-case letters.
I think this is what you were trying to write.
public class Scratchpad extends ConsoleProgram {
public void run() {
int[] test = {4, 7, 9, 7, 12};
int[] result = findMultipleOfThree(test);
System.out.println(Arrays.toString(result));
}
public static int[] findMultipleOfThree(int[] arr) {
int length = arr.length;
int[] result = new int[length];
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 3 == 0) {
result[i] = arr[i];
}
}
return result;
}
}
It looks like you're mixing up methods and classes. You can't declare an instance of a method, and they aren't types you can use for the type of a variable. If you want to call the method, you'd want to use something like int result = findMultipleOfThree(test); and print the result of that with System.out.println(result);
Hope this helps!
I have to calculate the sum of all the even numbers via an array.
In my exercise I am obliged to have two methods:
the first method is sum() and the second numEven().
I have an array below:
int[] array1 = {10,15,23,12,69,21,16,54};
My method sum() seems to be correct:
public static int sum(int[] array){
int number_sum = 0;
for(int i=0;i<array.length;i++){
number_sum += array[i];
}
return number_sum;
}
However, I have several problems with my method numEven()
I think that use a string is not good?
public static String numEven(int[] array){
String evenNumbers = "";
for(int i=0;i<array.length;i++){
if(array[i] % 2 == 0){
}
}
return evenNumbers;
}
Then, in my print() I have this:
System.out.println("The resultat is => " + sum(numEven(array1)));
My error message is:
Main.java:23: error: incompatible types: String cannot be converted to int[]
Do know you how to do a better method to find the even numbers?
Thank you for your help.
Yes, in this piece of code:
sum(numEven(array1))
First you calling numEven which returns String and then pass it as an argument to the sum method.
To make it work - change numEven method to return int[] array.
One of the ways is:
public static int[] numEven(int[] array) {
List<Integer> evenNumbers = new ArrayList<>();
for(int i=0;i<array.length;i++){
if(array[i] % 2 == 0){
evenNumbers.add(array[i]);
}
}
int[] result = new int[evenNumbers.size()];
for (int i = 0; i < evenNumbers.size(); i++) {
result[i] = evenNumbers.get(i);
}
return result;
}
If you have to keep the signature of numEven as you posted it (i.e, it should receive an array of int), then you have one of two methods:
1- you iterate over the array and create a new array of only even numbers and then call sum function to use it.
2- you iterate over the array and only add even numbers.
I'm putting here the solutions using the first method as it is better to use the sum code you already made.
Your code has a problem as it assumes it will use a string to add numbers.
public static int numEven(int[] array){
ArrayList<Integer> evenNumbers = new ArrayList<>();
for(int i=0;i<array.length;i++){
if(array[i] % 2 == 0){
evenNumbers.add(array[i]);
}
}
return sum(evenNumbers.toArray());
}
You can't pass a String to a method that takes an int[] public static int sum(int[] array).
In your case, I would consider using an ArrayList. An ArrayList is an object that is similar to an array but which you can add values to at any point. With an array, once you set the values, you can't change them, but with an ArrayList, you can keep adding values at any time.
First at the very top of your program, you need to import the ArrayList class from the java.util library:
import java.util.ArrayList
Next, here's what your numEven would look like:
public static int[] numEven(int[] array){
ArrayList<int> evens = new ArrayList<int>();
for(int i=0;i<array.length;i++){
if(array[i] % 2 == 0){
evens.add(array[i]);
}
}
return evens.toArray();
}
ArrayList initializes a new ArrayList of type int. evens.add() adds a value to the ArrayList. Notice at the end we have to return evens.toArray(), which converts the ArrayList back to a normal array of type int, because sum() is expecting an array of type int, and not an ArrayList.
I have a programming exam in a few days so I'm doing some exercises just to practice. However, I've been stuck with this problem and I started to doubt if it's possible to do it. Write a recursive method called arrayReverse which takes in an array of integers and returns said array in reversed sorted order. So an example would be:
input: [1,2,3]
output:[3,2,1]
I wasn't able to solve it. My intuition was to take the last element of the array, put it at the beginning, i,e: index[0] and then recursively call the rest of the array but then taking the new last element and put it on index[1]. Unfortunately, the implementation was harder than I thought but I (for the sake of trying) edited the question in a way that it accepts 2 arrays and this was my code:
import java.util.Arrays;
class Test {
int[] arrayReverse(int[] m, int[] mReverse) {
if (m.length == 1) {
mReverse[mReverse.length - 1] = m[0];
return mReverse;
} else {
int lastNum = m[m.length - 1];
mReverse[mReverse.length - m.length] = lastNum;
int[] arrayMinusOne = cropArray(m);
return arrayReverse(arrayMinusOne, mReverse);
}
}
int[] cropArray(int[] m) {
int[] mCropped = new int[m.length - 1];
for (int i = 0; i < m.length - 1; i++) {
mCropped[i] = m[i];
}
return mCropped;
}
}
void demo() {
int[] helpTest4 = new int[]{1, 2, 3};
int[] emptyArray = new int[helpTest4.length];
int[] test4 = arrayReverse(helpTest4, emptyArray);
System.out.println(Arrays.toString(test4));
}
public static void main(String[] args) {
new Test().demo();
}
}
It works perfectly but I'm not satisfied with the result because of two reasons:
I wasn't able to do it completely recursive. I used a for loop in cropArray.
I couldn't do it on one array.
How can this be done?
Option1: Using only one parameter (array) in the recursive function
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class MyClass {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int[] reversed = reverseArray(arr);
System.out.println(Arrays.toString(reversed));
}
public static int[] reverseArray(int[] arr)
{
if (arr.length == 0)
return arr;
// remove first element
int first = arr[0];
int[] list = Arrays.copyOfRange(arr, 1, arr.length);
//Calling Function Recursively get reversed array
int[] returnArr = reverseArray(list);
//Add original first to the last of the arrayToReturn
returnArr = Arrays.copyOf(returnArr, returnArr.length + 1);
returnArr[returnArr.length - 1] = first;
return returnArr;
}
}
Option2:
void reverseArray(int[] x){
reverse(x, 0, x.length -1);
}
void reverse(int[] x, int i, int j){
if(i<j){//Swap ith with jth element where i and j are equidistant from ends
int tmp = x[i];
x[i] = x[j];
x[j] = tmp;
reverse(x, ++i, --j);//Recursive
}
}
Test:
int[] s = new int[]{1,2,3,4,5};
reverseArray(s);
System.out.println(Arrays.toString(s));//"5,4,3,2,1"
Recursive, O(n), no temporary Array needed.
Please try the code below:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[]= new int[n];
for(int i=0;i<n;i++)
{
arr[i] = sc.nextInt();
}
Printsum(arr,0);
}
public static void Printsum(int arr[], int idx)
{
if(idx == arr.length)
return ;
Printsum(arr,idx+1);
System.out.println(arr[idx]);
}
}
I don't think this is a particularly good question - there is obviously a direct and clear way to do it without recursion; so the question does little to demonstrate any useful knowledge of recursion.
That said I believe the algorithm they were seeking uses the facts that:
a) reversing a 1 length array is trivial
b) you can reverse an n length array by appending the first element to the reverse the the last n-1 elements.
So code for this solution will look much simpler that what you currently have.
Ruby:
def reverse(a)
if a.empty?
return []
else
return [a.last] + reverse(a[0..-2])
end
end
a = [1, 2, 3]
reverse(a)
Taking the request literally, I have come out with a solution which only needs ONE recursive function with just ONE input/output parameter:
public static void arrayReverse(int[] input)
{
if (input.length > 0)
{
// Store locally the fist element:
int firstElement=input[0];
// Creates a sub-array and reverses it:
int[] input2=new int[input.length - 1];
System.arraycopy(input, 1, input2, 0, input2.length);
arrayReverse(input2);
// Copies back the reversed array into the current array:
System.arraycopy(input2, 0, input, 0, input2.length);
// Puts the stored fist element in the last position:
input[input.length - 1]=firstElement;
}
}
This solution is based upon a stack structure, for which it takes advantage of the machine calling stack at runtime, where the local values are stored while the function is executing.
The base case of this recursion is, of corse, the empty array.
In the generic case, the function stores locally the first element, then re-invokes itself recursively to reverse the rest of the array, and last, puts back the first element in the last position.
I'm trying to return the positive numbers in an array. I'm new to arrays and am having trouble figuring it out.
public class PossitiveArray
{
public static void main(String[] args) {
int[] numbers = {2,-1,5,-4,3};
System.out.print(numbers);
}
public static int[] getPositiveNumbers(int[] numbers)
{
for (int n : numbers)
{
if(n>0)
{
int [] nums = numbers;
}
}
return nums;
}
}
Analysis-
This is what I came up with. As it is right now it gives me and error saying I need to make a local variable for nums but when I do that it returns "[I#677327b6". I tried to make it return numbers but i'm not sure what to put into the if statement.
Required-
The goal is to just have positive numbers returned. Any help would be appreciate I am very knew to arrays and programing in general.
Java 8's streams would make this take much easier:
public static int[] getPositiveNumbers(int[] numbers) {
return Arrays.stream(numbers).filter(i -> i > 0).toArray();
}
Regarding printing the result - you're seeing the default toString(), as int[] does not override it. Instead, you could use Arrays.toString to print the result.
Use below Code-
public class test
{
public static void main(String[] args) {
int[] numbers = {2,-1,5,-4,3};
for(int n : getPositiveNumbers(numbers)){
System.out.print(n);
}
}
public static int[] getPositiveNumbers(int[] numbers)
{
int count = 0;
for (int n : numbers)
{
if(n>0)
{
count++;
}
}
int [] nums = new int[count];
int i =0;
for (int n : numbers)
{
if(n>0)
{
nums[i] = n;
i++;
}
}
return nums;
}
}
There are a few things to consider here to answer your question.
Variable scope of nums is local to the loop. This means that nums will be deleted each time the for-loop iterates, and will be gone when the loop ends. You can address this by moving the declaration to before the for-loop.
Your declaration int[] nums only declares that nums is an array of ints, but doesn't allocate any space to put anything into the array. You must allocate the space using for example int[] nums = new int[5], which creates an array of 5 slots. In your case, you'll want an array that will hold all the positive numbers, which at most will be the entirety of the input array. Use int [] nums = new int[numbers.length] to accomplish this (but see next point).
How do you want to fill the new array nums containing only the positive integers? The way you have it written it looks like you would like {2,-1,5,-4,3} to return {2, 5, 3}, or would you rather it return {2,0,5,0,3}. Either case will affect how your for-loop should handle nums. For an output of {2, 5, 3} the size of the array needs to figured out beforehand by counting the number of positive entries first.
NOTE: This problem could be solved more easily using linked lists, where size is handled dynamically.
Here is a solution that replaces negatives with zeros.
class PossitiveArray {
public static void main(String[] args)
{
int[] numbers = {2,-1,5,-4,3};
System.out.print(Arrays.toString(getPositiveNumbers(numbers)));
}
public static int[] getPositiveNumbers(int[] numbers)
{
int [] nums = new int[numbers.length];
for(int i = 0; i < numbers.length; i++)
{
if(numbers[i] > 0)
{
nums[i] = numbers[i];
}
else
{
nums[i] = 0;
}
}
return nums;
}
}
The problem I am trying to solve is as follows:-
Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}
I came up with the following code:-
public int[] rotateLeft3(int[] nums) {
for(int i=0;i<2;i++)
swap(nums[i],nums[i+1]);
return nums;
}
public void swap(int a,int b)
{
int temp = a;
a = b;
b= temp;
}
However, it is not running successfully. In case of C++, I could have passed references as arguments and the problem would have been sorted then why is not happening here?
The following code is working:-
public int[] rotateLeft3(int[] nums) {
int temp = nums[0];
nums[0] = nums[1];
nums[1] = temp;
temp = nums[1];
nums[1] = nums[2];
nums[2] = temp;
return nums;
}
But this code is complete brute-force writing and I am not liking it very much. Can you please suggest how I can make the first approach work?
All parameters in java method calls are passed by value. You need to pass in the array and the two indexes you want to swap.
public void swap(int[] array, int a,int b)
{
int temp = array[a];
array[a] = array[b];
array[b]= temp;
}
As you have said the problem is passing by reference, C does it - Java doesn't. There are plenty of other ways to achieve the same ends though.
The simplest way is to pass the array and the two indexes to your swap function rather than the contents of the array at that index.
If you want a rotation that isn't limited by size, try:
public int[] rotateLeft(int[] nums){
if(nums.length == 0)
return new int[0];
int temp = nums[0];
//This loop starts at index 1 because we are moving
// elements left, and 0 can't move left.
for(int index = 1; index < nums.length; index++){
nums[index-1] = nums[index];
}
nums[nums.length-1] = temp;
}
you can also use the xor swap without the temp variable ;)
public void swap(int[] array, int ind1, int ind2) {
array[ind1] ^= array[ind2]
array[ind1] ^= (array[ind2] ^= array[ind1])
}
When you call the swap method , you are passing the values inside your array, but that method does not return the a and b values. Yes, that could be done in C/C++ with the use of pointers, but java does not have it.
Xynariz's code provide a way of doing the shift that is not limited to array size.
You can create a swap function with a single line usage pattern, but the calling format is not typical:
public int[] rotateLeft3(int[] nums) {
for(int i=0;i<2;i++)
nums[i+1] = swap(nums[i], nums[i]=nums[i+1]);
return nums;
}
// swaps any number of same type objects
public <T> T swap(T... args) {
// usage: z = swap(a, a=b, b=c, ... y=z);
return args[0];
}
This works because the first argument is passed into swap before the assignments happen in rest of the arguments.