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.
Related
i want to write a recursive method that prints the sum of occurrences in an array without using loops in the method.
for example if the method get array - arr{1,1,2,3,3,3,3}
the method will print 1:2 2:1 3:4
for this i write a few method
first method that sort the array
seconed method that get array index and the number in this index and return the next index of different number for example to the array above the funcJump(arr,1,1)
will return 3 beacuse thats the first index of different num for 1.
what i think to do to solve this problem is first use the function to sort the array and then to write two punctions
public static void printFrequencies(int[]arr)//will print
public static int printFrequencies(int[]arr,int ix){//scan the array and send
to the void function the sum of occurences
what i think is to use the function "jump" to get the different indexes and send them to the void function for print but i really stuck to apply this way of thinking to my program.
what do you think thats a good idea?
how can i applay this in my program?
public void printFrequencies(Integer[] array){
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
for(int i = 0 ; i<array.length;i++){
Integer temp = array[i];
Integer count = map.get(temp);
if(null == count){
map.put(temp, 1);
}else{
map.put(temp, map.get(temp)+1);
}
}
for(Integer key : map.keySet()){
System.out.println(key+":"+map.get(key));
}
}
I read your code, and I think it's better to understand, and in order to remove duplicate items, I used map.
public class Part01 {
public static void main(String[] args) {
int[] nums = {1,2,2,1,1,3,3,4};
Part01 part01 = new Part01();
part01.countAllNumber(nums);
}
public int countNumber(int[] nums,int num){
int count = 0;
for(int i = 0;i < nums.length;i++){
if(nums[i] == num)
count++;
}
return count;
}
public void countAllNumber(int[] nums){
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < nums.length;i++){
int count = countNumber(nums, nums[i]);
map.put(nums[i], count);
}
for(Integer key : map.keySet()){
System.out.println(key+":"+map.get(key));
}
}
}
I have a function that generates random arrays:
private static List<Integer> randomIntegerArray(int n) {
int[] array = new int[n];
for(int i = 0; i < array.length; i++) {
array[i] = (int)Math.random();
}
return array;
}
I'm getting the following error:
incompatible types: int[] cannot be converted to java.util.List
I'm not sure what the issue is here. This is an incredibly simple bit of code that I can't seem to get to work.
You're returning List<Integer>, but you're creating an int[]. They're completely different things! try this instead:
private static List<Integer> randomIntegerArray(int n) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
list.add((int) Math.random()); // always returns 0
}
return list;
}
Or if you definitely want to use an array, change the method's declaration:
private static int[] randomIntegerArray(int n)
And be aware that Math.random() returns a value between 0 and 1, if you convert it to an int it'll always be 0.
You can have simpler code that actually produces random integers instead of zeros by directly using the Random class:
private static List<Integer> randomIntegerArray(int n) {
return ThreadLocalRandom.current().ints(n).boxed().collect(Collectors.toList());
}
This may return any Integer value; you can specify a range with additional arguments to the ints() method.
An alternative to Oscar's answer would be:
private static int[] randomIntegerArray(int n) {
int[] array = new int[n];
for(int i = 0; i < array.length; i++) {
array[i] = (int)Math.random();
}
return array;
}
As others have said, a List of type Integer is not the same thing as an array of type int.
Probably this wouldn't be the best choice but also works, altough you'll get always a zero list of integers as Peter Lawrey says:
private static List<Integer> randomIntegerArray(int n) {
Integer[] array = new Integer[n];
for(int i = 0; i < array.length; i++) {
array[i] = Double.valueOf(Math.random()).intValue();
}
return Arrays.asList(array);
}
Your error tells you that arrays and list are not compatible, a quick search would have shown you ways to convert one to the other like Arrays.asList ().
Secondly Math.random returns a random number between 0.0 and 0.9 so you need to multiply by the number you want.
You may need to go through a quick tutorial on Java first.
All the best.
I'm new to java and was looking for some advice. I was assigned the problem below and I cannot get the compare method to run for the life of me. It won't compile. I receive the following error:
error: method compare in class Plateau cannot be applied to given types;
compare(a[N]);
required: int[],int
found: int
reason: actual and formal argument lists differ in length
Any help would be greatly appreciated.
1.4.21 Longest plateau. Given an array of integers, find the length and location of the longest contiguous sequence of equal values where the values of the elements just before and just after this sequence are smaller. The array should be passed to a method and the results should be printed to the screen.
public class Plateau{
public static void main(String[] args) {
int N = args.length;
int[] a = new int [N];
for (int i=0; i < N; i++){
int number = Integer.parseInt(args[i]);
a[i]=number;
}
compare(a[N]);
}
public static void compare(int[] a, int N){
int comp = a[0];
int current_length=0;
int max=0;
int maxlength=0;
for(int l=0; l < N; l++){
if (a[l] > comp){
current_length = 0;
comp = a[l];
max = a[l];
}
if (a[l] == comp){
current_length+=1;
comp = a[l];
}
else if (a[l] < comp && a[l] < max){
comp = a[l-1];
current_length=maxlength;
l++;
}
}
System.out.println(max);
System.out.println(maxlength);
}
}
It is quite obvious: the arguments expects an array and a value (length? index), but you are just passing one value from the array.
Just turn
compare(a[N]);
to
compare(a, N);
The problem is an issue with parameters and method signature. As I can see that you are learning, I will not give you a full solution. I will only point you to a way to solve it
The method compare expects two parameters int[] a, int N, but you are only calling it with one compare(a[N])
a[N] is wrong, because it would index an element outside of the array (mind that array index goes from 0 to N-1)
a is the array of type int[], so you need to use this as the first parameter of the call to compare
N is the number of elements (of type int) in the array, so this could be the second parameter
Your method signature doesn't match the way you are trying to invoke it. In your main method, you are trying to call a method called compare that takes an array of integers, but the only definition you have is for a compare method that takes both an array of integers and a single integer. The usage and definition need to be consistent, or the compiler won't know what you are trying to do.
Your method
public static void compare(int[] a, int N){
takes two parameters one is integer array and other is a integer
When you call that method in your main method you are passing only one parameter
public static void main(String[] args) {
int N = args.length;
int[] a = new int [N];
for (int i=0; i < N; i++){
int number = Integer.parseInt(args[i]);
a[i]=number;}
compare(a,N); // pass a integer along with your integer array (you have to use your array variable which is a and not a[N])
}
and thats why you are getting that error pass an integer along with that and it will work
Also you are passing the array incorrectly
int[] a = new int [N];
you have declared array here and thus you need to pass the variable a and not a[N]
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.
public class negativeTest {
public static int Negativenum (int[] array) {
int negative = 0;
for (int i = 0; i < array.length; i++){
if(array[i] < 0){
negative = negative + 1;
}
System.out.println(negative);
}
}
}
I am trying to count how many elements in array are negative. This is what i have so far. My question is: eclipse is telling me that i should return a void instead of static int? How can i do this without using void?
I'd want to use
public static int negativenum(int[] array){
Only way i can get this working is create an array with positive and negative numbers and count them, but i want to be able to have method that does that without creating array of numbers. Can you help me?
Try giving a return statement , your method is expecting a int as a return parameter.
Therefore it will give compiler error.
public class negativeTest {
public static int Negativenum (int[] array) {
int negative = 0;
for (int i = 0; i < array.length; i++){
if(array[i] < 0){
negative = negative + 1;
}
System.out.println(negative);
}
return negative;
}
}
Ther error you are getting is because you have not declared the main function inside the class.
You have to call Negativenum from the main function.
you can do it like this :
public static void main (String args[])
{
negativeTest nt = new negativeTest();
int [] array = new int[]{ 100,200 };
int count = nt.Negativenum(array);
System.out.println(count); // It will print **2**
}
Regarding your doubts you have asked in comments.
You have to return anything from function only when you want to use that use that return value from the calling function.
Otherwise if you want to just print that value on console or log that value , you can easily do it in the negativeTest function and you can change the return type of this function to void.
FYI , you should not begin your classname with the lower case character.
The error is because you are not returning anything from the function which is expected to return an int.
If you want the function to count the number of negative numbers and return the count so that the caller of the function gets the count, you can add an
return negative;
before the end of the function.
Alternatively if you don't want to return anything from the function and want to just print the count as part of the function call, you can change the return type of the function from int to void:
public static void Negativenum (int[] array) {
Your function signature suggest a return type of int, but you aren't returning anything from the function. I suspect this is why Eclipse is suggesting you change the function signature to return void.
If you add return negative; it should avoid the notice from Eclipse.
If your intention is to simply print the count, then you should change the return type.
if you dont want to return anything, set your method signature to void, but add an out variable, like so:
public static void NegativeNum(int[] array, out int negative)
{
negative = 0;
foreach(int i in array) { if (i < 0) negative++;
}
then you just declare negative wherever this method is called from, and pass it in as an out variable:
int negative = 0;
NegativeNum(array, out negative);
After that call, negative will contain the count of negative numbers determined by the method.