create a method that can count negative numbers in an array - java

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.

Related

Create a method sum() and another method numEven()

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 couldn't create a method to count the number of occurrences

I've created a method to count the number of occurrences in an array, but I can't compile and run it.
Compiler gives the error:
The method occurence(int[]) in the type countOfOccurence is not applicable for the arguments (int)
public class countOfOccurence {
public static void main(String[] args) {
int[] number = {15,16,14};
System.out.print(occurence(number[15]));
}
public static int occurence(int[] number) {
int count = 0;
for(int i = 0 ; i < number.length; i++) {
for(int k = 0 ; i < number.length; i++) {
if(number[k] == number[i]) {
count++;
}
}
}
return count;
}
}
Your occurrence method is expecting an array, but you are just passing an int to it (the 15th element from your array, which will also cause a runtime error as there are only 3 elements in your array).
But I also think your logic is off here, your current method (given that it would compile) will count all occurrences of all duplicate numbers in your array, not just the number you would want.
First off all, your occurrence method would need 2 arguments, the actual array and the number you want to count the occurrences of. You don't need an inner loop, just keep your outer loop and check inside whether the array element equals your desired number.
public static void main(String[] args) {
int[] number = {15,16,14};
System.out.print(occurence(number, 15));
}
public static int occurence(int[] numberArray, int number) {
int count = 0;
for(int i = 0 ; i < numberArray.length; i++) {
if(numberArray[i] == number) {
count++;
}
}
return count;
}
Of course there are better / cleaner ways to count occurrences of elements in an array, for example using the Streams api, if you would want to optimize.
occurence(int[] number) function accepts the integer array parameter. And, you are calling the function with occurence(number[15]). By number[15], it means 15th-index position from number array, which is also not valid in your code.
For your scenario to work, occurence function should be changed to accept two parameters like public static int occurence(int[] numbers, int number). And, call it by occurence(number, 15).

How does Linear Recursion work?

I have written a java program to add elements in an array using Linear Recursion. The output obtained is not as expected. Can anyone point what is wrong with this program?
public class TestSum {
public int count = 0;
public int sum(int[] a){
count++;
if(a.length == count){
return a[count -1];
}
return sum(a) + a[count -1] ;
}
public static void main(String[] args) {
int[] a = {1,2,3};
int val = new TestSum().sum(a);
System.out.println(val);
}
}
I am expecting the output as 6 but obtained is 9. What is wrong?
Strangely if I change the order of addition i.e. return a[count -1] + sum(a); then it gives output as 6.
Generally, recursive programs that are not re-entrant (i.e. relying on external state) are suspicious. In your particular case count will change between invocations of sum, making the behavior hard to trace, and ultimately resulting in the error that you observe.
You should pass the index along with the array to make it work:
// The actual implementation passes the starting index
private static int sum(int[] a, int start){
if(a.length == start){
return 0;
}
return sum(a, start+1) + a[start];
}
// Make sure the method can be called with an array argument alone
public static int sum(int[] a) {
return sum(a, 0);
}
Unlike an implementation that increments the count external to the method, this implementation can be called concurrently on multiple threads without breaking.

New to Java, Method X in class y cannot be applied

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]

Don't understand error message

public class ArrayPrac {
public static void main(String[] args) {
int[] arrayOne = {2, 3, 4, 5, 6};
System.out.println(findMin(arrayOne));
}
public static void findMin(int[] list) {
int minValue = list[0];
int i = 1;
for( i = 1; 1 < list.length; i++);
if(list[i] < minValue) {
minValue = list[i];
}
}
}
In the System.out.print part in line 6 it wont run and gives me the compiler error:
The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
I seem to have searched for an answer all day, so now I post my specific case.
Cheers.
Fix this, at the end of your findMin() method you must return the minimum value that was found:
return minValue;
And consequently, the method signature must be changed, too:
public static int findMin(int[] list)
It makes sense: if the findMin() method does all that hard work to find the minimum value, the end result must not be left as a local variable, it won't be useful outside if you don't return it after the method invocation ends.
There's another hard-to-find bug lurking, by the way. Remove the ; at the end of the line with the for, and put the contents of the loop inside a pair of {}. Currently, the loop is empty, and the lines after the for lie outside the loop. And the loop condition is wrong, too! here's how the method should look after all the problems are fixed:
public static int findMin(int[] list) {
int minValue = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] < minValue) {
minValue = list[i];
}
}
return minValue;
}
System.out.println takes a String input but you are passing a void. As your method findMin returns void. This is causing the compiler error.
Now speaking about the logical problem, you may want to display the output of findMin method but the method does not return anything. So returning minValue may make sense here.
Once you return the int value from minValue method then you can display the result by concatenating it to a an empty string. Something like this:
System.out.println("" + findMin(arrayOne));
The method findMin() is declared as returning type void: Either declare it to return something (and return something),
public static int findMin(int[] list) {
int minValue = list[0];
int i = 1;
for( i = 1; 1 < list.length; i++)
if(list[i] < minValue) {
minValue = list[i];
}
return minValue;
}
Note fixing bug: removing semicolon from after for()

Categories