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]
Related
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'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).
I want to make a program which, after filling an array in main(), through a method, returns the arithmetic mean of the elements contained in that array.
When I call the method to execute the process (the line where I use the System.out.print) it gives me an error, saying that the method is not applicable for the arguments in it. But it should lead to an array of ints.
Code
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
System.out.println(meanArray (2, 6, 9, 19, 1));
}
static int meanArray (int [] a) {
Scanner inputLine = new Scanner(System.in);
int numbers;
int start;
int sum = 0;
int mean;
numbers = inputLine.nextInt();
for (start = 0; start < numbers; start++) {
a[start] = inputLine.nextInt();
sum = sum + a[start];
}
mean = sum/numbers;
return mean;
}
}
When you call
System.out.println (meanArray (2, 6, 9, 19, 1));
it expected a method with a signature like
public static Something meanArray(int a, int b, int c, int d, int e) {
Most likely what you intended was
public static Something meanArray(int... a) {
which accepts a variable number of arguments.
The problem in this code is you create a method that take an integer array as parameter and you send different integer values but not an integer array when calling the method. Instead calling;
meanArray(1,2,4,3)
you should declare integer array and pass the variable to the method.
It will be better to declare array variable first and pass it to the function like:
int a[]={1,2,3,4};
meanArray(a);
And you donot need to declare another numbers variable ( lenth is inbuilt function to return size of an array)inside the method for summing elements of array, try as follows inside the meanArray();
for(start=0;start<a.length;start++){
sum+=a[start];
}
If you want to test the numbers in your code, declare and initialize the array with:
int[] array ={2,6,9,19,1}; and then call meanArray(array);
If you want to test an arbitrary set of numbers from console, you need to declare the array differently with:
int[] array = new int[5]; //*5 states how many numbers you will input from console *
and then you need to change the loop interval to: start < array.length;
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.
I am new to programming and Java and trying to write a program which takes two arrays as input and reports back their sum. I want to do this by creating a class which takes two arrays as constructor inputs and then creating a method that adds them together and a method which prints out this new sum array.
Here is my class:
public class test1 {
int [] a;
int [] b;
int [] final23;
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
}
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
return final23;
}
public void print()
{
for (int i = 0; i < final23.length; i++)
{
System.out.println(final23[0]);
}
}
}
Here is my main class:
public class main1 {
public static void main(String[] args)
{
int l[] = {4,7,2};
int k[] = {4,6,2};
test1 X = new test1(k,l);
X.sum(k,l);
X.print();
}
}
I keep getting an error when I run this through:
Exception in thread "main" java.lang.NullPointerException
at test2.sum(test2.java:17)
at main1.main(main1.java:8)
I guess what I really want is for my sum method to take a test1 object as input. However, I don't know how to do this.
Your variable final23 is never initialized.
In java you have to initialize an array before using it. Either you do it during the declaration (like you did with k and l) or you have to do it later with a new arrayType[arraySize];
Here are the way an array can be declared/initialized.
int[] iArray = {1, 2, 3}; //Declaration, Initialization, set values
int[] iArray; //Declaration
iArray = new int[3]; //Initialization
iArray[0] = 1; //Set value
int[] iArray; //Declaration
iArray = new Array[3]{1, 2, 3}; // Initialization and set values
You can of course for the two last sample put the initialization on the same line that the declaration.
Try this (cleaned) code :
public class test1 {
int[] final23;
public int[] sum(int[] x, int[] y) {
final23 = new int[Math.min(x.length, y.length)];
for (int i = 0; i < final23.length; i++) {
final23[i] = x[i] + y[i];
}
return final23;
}
public void print() {
for (int aFinal23 : final23) {
System.out.println(aFinal23);
}
}
public static void main(String[] args) {
int l[] = {4, 7, 2};
int k[] = {4, 6, 2};
test1 x = new test1();
x.sum(k, l);
x.print();
}
}
Resources :
Oracle.com - Arrays
JLS - Array Initializers
JLS - Array Creation Expressions
I'm going to take a long shot here
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
return final23;
}
As a side comment, I'm guessing that you want to add all of the elements of the vector, not just the first. Change your for-loop body to:
final23 [i]=x[i] + y[i] ;
What's final23? Where is it created?
Try adding this to your constructor
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
this.final23 = new int[Math.min(a.length, b.length)];
}
Now final23 is defined and created, and you can use it in your class.
If you supply test1 with arrays in the ctor, you don't need them in the sum method, just use the ones you have in the class already:
public int [] sum()
{
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [i]=a[i] + b[i] ;
}
return final23;
}
You also had an error in the sumation, you didn't use the iteration variable, you also need to initialize final23 in the ctor.
You have to initialize final23 array before putting elements in it (on line 17).
**final23 = new int[Math.min(x.length, y.length)];**
for (int i = 0; i < Math.min(x.length, y.length); i++)
{
final23 [0]=x[0] + y[0] ;
}
I see a couple of things to point out here.
public test1 (int x [], int y [])
{
int [] a = x;
int [] b = y;
}
First of all, remember that each test1 object - that is, each instance of your test1 class - has variables named a and b. I'm guessing that in the constructor, you want to take the arrays x and y which were passed as parameters and store them into a and b of the object. To do that, all you have to do is write
a = x;
b = y;
You don't have to write int[] again, not when you just want to access an existing array-type variable. You only write that when you're creating a new array-type variable. In this case, when Java sees that you've written int[] a in the constructor, it thinks you want to create yet another array-type variable named a, separate from the one in the test instance, and that's the one that gets set equal to x. The thing is, that local variable gets lost at the end of the constructor. So you're left with a test1 instance that has variables a and b that still refer to nothing, i.e. they're null.
By the way, since you're going to be using the array final23 later on, you should initialize it. Right now, it refers to null because you never set it to equal anything else. You'll need to create a new array and store it in that variable in order to be able to use it later on. So put this line in your constructor:
final23 = new int[Math.min(a.length, b.length)];
That creates the new array with a length equal to the shorter of the two arrays passed in.
Moving on:
public int [] sum(int [] x, int[] y)
{
int [] a = x;
int [] b = y;
In this bit of code, you have the same issue as in the constructor: you create two new array-type variables a and b that get used instead of the ones in the test1 object. I don't think that's what you meant to do. So I'd say get rid of those last two lines entirely.
There's another problem, though: if you think about it, you still have two arrays stored in the test1 object. Assuming you've fixed your constructor, those are the same two arrays that were passed to the constructor. And now you're getting two new arrays under the names x and y. So you have four arrays total. Which ones did you want to sum up? I'm guessing that you meant to sum the two arrays that were passed to the constructor. In that case, your sum method doesn't need to - and shouldn't - accept more arrays as parameters. Get rid of the parameters x and y, so your sum method just looks like
public int [] sum()
{
Now you have to change the rest of that method to use a and b, starting with the for loop. Change its opening line to this:
for (int i = 0; i < Math.min(a.length, b.length); i++)
{
I notice you were wondering how to get your sum method to take an instance of test1. Well, in a way it actually does. There's a special hidden parameter passed to all methods (except static ones) that contains the object the method was called on - in fact, using your main program as an example you could kind of think of X.sum(k,l); as actually calling test1.sum(X,k,l);, where X is the special hidden parameter. You can access it inside the method using the name this (so you could write this.a instead of just a), but Java is generally smart enough to do that for you.
In the body of the for loop, you have another problem. What you want to do is add up corresponding elements of the arrays, i.e. a[0] + b[0] goes into final23[0], a[1] + b[1] goes into final23[1], and so on. But inside the for loop, you only ever add up element 0 of each array. You need to use the loop index variable i, because that runs through all the values from 0 to the length of the shorter array minus 1.
final23 [i] = a[i] + b[i];
}
return final23;
}
So the first time the loop runs, i will be 0, and you'll set final23[0] = a[0] + b[0]. The next time it runs, i will be 1, and you'll set final23[1] = a[1] + b[1]. And so on.
The same problem occurs in your print method. Each time through the loop, you always print out final23[0], when you really should be printing out final23[i] because i changes each time you go through the loop. Change it to
public void print()
{
for (int i = 0; i < final23.length; i++)
{
System.out.println(final23[i]);
}
}
At this point your program should be working, I think, but there are still some improvements you could make to its design. For one thing, every time you create an object of test1, you know you're immediately going to call sum on it. So why not just put the summing-up code right into the constructor? That way you know that the sum will be computed right when you create the object, and you don't have to call sum explicitly.
Of course, once you do that, you'll have no way to access the array final23 from your main class - except that if you want to print it, you can call the print method. But what if you want to write a main class that, say, adds up two arrays, and then adds the result to a third array? It'd be nice to have a way to get the result from the test1 instance. So you can add an accessor method, possibly named getFinal23, that just returns the sum array final23.
In practice, this operation of adding two arrays would probably be implemented as a static method. So if you want, you could try starting over, and writing it as a static method. (Remember that a static method is one which doesn't receive a special hidden parameter) Inside the static method, you'd have to create the final23 array, go through the loop to compute the sums, and then return the array you created. You'll need to enclose the static method in a class, of course, but that class doesn't have to have a constructor since you never really use it for anything. It'd look something like this:
public class SumClass { // pun intended ;-)
public static int[] sum(int[] x, int[] y) {
// you fill in this part
}
}