Adding numbers to arrays with methods in another class? - java

I am learning java and trying to figure out how to implement these methods into my main class from a second class. The program takes user input to add numbers into an array and then I need to print the following using the pre-specified methods below. The parameters in the below method is what confuses me.
public static double findMin(double[] numbers, int count) //count is the count of numbers stored in the array
public static double computePositiveSum(double[] numbers, int count)
public static int countNegative(double[] numbers, int count)
Basically, I am confused as to how I link all the variables and array between the two classes so they can recognize the parameters and return the correct value to output min, sum and number of negatives. Do I want the array in the main method?
Basically, what I did now to fix it was that I created the variables in the main method and then pass the variables in the main method through the parameters of the object I created that links to the secondary class. Does that seem ok?

If you already have the array , so what you need is call your methods and pass this value to it
lets say you have this array :
double[] num = {1.2,2.3};
and your count is the length of num array , so the count is:
int count = num.length;
then call your method and pass the parameters to it like this:
findMin(num , count );
computePositiveSum(num , count );
countNegative(num , count );
Note : you need to read in Object-Oriented Programming Concepts

Sorry guys for such a question. I just needed a refresher since it has been awhile. I resolved the issue by creating the array and count variable in the main method and then passed those through the parameters so the methods in the secondary class could read them. Thanks for the quick responses and help .

You don't need a count variable, you can use myarray.length
So your code should be something like this:
public static void main(string [] args)
{
double[] myarray = {5.3, 69.365, 125, 2.36};
double result = MyClass.findMin(myarray);
}
public class MyClass
{
public static double findMin(double[] numbers)
{
// your impl
}
public static double computePositiveSum(double[] numbers)
{
// your impl
}
public static int countNegative(double[] numbers)
{
// your impl
}
}

You can create an object reference of the main class in your derived class. Then call these methods using the object of your main class.
class Main
{
------
}
class derived
{
Main m = new Main();double[] A=new double[1];
Scanner s = new Scanner(System.in);
int i=0,wc=1;
int arrayGrowth=1;
while(s.hasNext())
{
if (A.length == wc) {
// expand list
A = Arrays.copyOf(A, A.length + arrayGrowth);
wc+=arrayGrowth;
}
A[i]=s.nextDouble();
i++;
}
int len=A.length-1;
m.findMin(A,len);
m.computePositiveSum(A,len);
m.countNegative(A,len);
}

Related

How to call a static method from main class?

I got this code:
public static ArrayList<Integer> MakeSequence(int N){
ArrayList<Integer> x = new ArrayList<Integer>();
if (N<1) {
return x; // need a null display value?
}
else {
for (int j=N;j>=1;j--) {
for (int i=1;i<=j;i++) {
x.add(Integer.valueOf(j));
}
}
return x;
}
}
I am trying to call it from the main method just like this:
System.out.println(MakeSequence (int N));
but I get an error...
Any recommendations? Much appreciated, thanks!
System.out.println(MakeSequence (int N));
should be
int N = 5; // or whatever value you wish
System.out.println(MakeSequence (N));
Just pass a variable of the correct type. You don't say that it is an int again;
You define the method as follow MakeSequence (int N), this means that method expects one parameter, of type int, and it'll be called N when use inside the method.
So when you call the method, you need to pass an int like :
MakeSequence(5);
// or
int value = 5;
MakeSequence(value);
Then put all of this in a print or use the result in a variable
System.out.println(MakeSequence(5));
//or
List<Integer> res = MakeSequence(5);
System.out.println(res);
All of this code, to call the method, should be in antoher method, like the main one
Change x.add(Integer.valueOf(j)); to x.add(j); as j is already an int
to follow Java naming conventions : packages, attributes, variables, parameters, method have to start in lowerCase, while class, interface should start in UpperCase
The first issue is I think that N should be some int value not defining the variable in the method call. Like
int N = 20;
ClassName.MakeSequence(N);
The other issue you will face. As System.out.println() only prints string values and you are passing the ArrayList object to it, so use it like this System.out.println(ClassName.MakeSequence(N).toString())

What is the difference between void and return even though I can get same output on both?

i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.

What will public static int[] main (int[] ) return and where? [duplicate]

This question already has answers here:
Can a main method in Java return something?
(6 answers)
Closed 8 years ago.
class Half {
public int evaluate(int arg) {
return arg/2;
}
}
public class Box {
public static int [] main (int[] arrIn) {
int[] arrOut = new int[arrIn.length];
Half func = new Half();
for (int i=0; i< arrIn.length; i++)
arrOut[i] = func.evaluate(arrIn[i]);
return arrOut;
}
}
So contents of arrOut are the elements in arrIn divided by two.
I want to take integer array from command line arguments and print array with new contents to screen.(I don't want to take it as string values then convert to int and blah blah)
Is there any way to take direct integers as arguments?
Secondly the above code gives an error.(Obviously)
Error: Main method not found in class Box, please define the main method as:
public static void main(String[] args)
Which brings me to my next question.
Should it always be public static void main(String[] args)? Can't it be public static int main with some arguments other than string type?(Don't explain the static part.. As per my understanding main method needs to be invoked without an object which is why it is static. but if it is forced(somehow) to return an integer, where will it return it?(I mean to which method? or will it directly print to the screen?)I know it doesn't print to the screen (duh!) but then where is the control returned basically after main method finishes execution?
Should it always be public static void main(String[] args)?
Yes, if you want it to act as an entry point.
Can't it be public static int main with some arguments other than string type?
No. Section 12 of the JLS explains JVM start-up, and includes this in 12.1.4:
Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.
The method main must be declared public, static, and void. It must specify a formal parameter (ยง8.4.1) whose declared type is array of String.
Basically, the only bits which are optional are:
The name of the parameter
Whether you make it a varargs parameter or not
You can overload the method if you want, providing extra main methods with different parameter types and possibly a return value - but only the void one with a String[] parameter will be treated as an entry point.
I want to take integer array from command line arguments and print array with new contents to screen.(I don't want to take it as string values then convert to int and blah blah) Is there any way to take direct integers as arguments?
No. You have to do it yourself. It's pretty trivial though:
int[] integers = new int[args.length];
for (int i = 0; i < args.length; i++)
{
integers[i] = Integer.parseInt(args[i]);
}
First thing first:
This must always be public static void main(String[] args)
Second to read integer directly, use:
Scanner in = new Scanner(System.in);
int num = in.nextInt();

return the maximum value in the array?

I had an an assignment with this question
Write a function maxArray which receives an array of double's and returns the maximum value in the array. using this function
double maxArray(double dar[], int size);
I did what he want and I had problem with the calling sentence within the main method !!
here is my code :
public class Q3 {
public static void main(String[] args) {
double dar[] = { 22.5 , 10.23 , 15.04 , 20.77 };
double max = maxArray(dar,4);
System.out.println("the largest number is : " + max);
}
double maxArray(double dar[], int size) {
double maxV = 0;
for (int i = 0; i < dar.length; i++) {
if (dar[i] > maxV ) {
maxV = dar[i];
}
}
return maxV;
}
}
The reason you can't call your method from main() is that main() is static whereas your method isn't.
Change it to:
static double maxArray(double dar[], int size)
While you're at it, remove size since it's not necessary.
It is probably also worth noting that your method would fail if the array were to contain negative numbers.
your maxArray method is a non static method. you cannot access non-static methods from static methods without an instance of the class, you should create an instance of your class and call maxArray method
double max = new Q3().maxArray(dar,4);
Or alternatively, you could always mark your maxArray method static and call it directly from main method.
Declare your maxArray as static, so you can access it as from a static method main()
or
You create an instance of your class and call it from the object.
your issue is you are trying to call maxArray, a non-static method, from your main method, which is static. That's a problem because a non-static method can only be called from an instance of the class, whereas a static method is called via the class itself.
Either make your maxArray a static method, or initialize a Q3 object in your main method, and call maxArray like that.
Your method has to be static, so you have to say
static double maxArray(double dar[], int size)
Here are some hints how you could improve your method:
since you don't use the value "size" once, you can either throw it out or replace the i < dar.length with i < size.
Also, when initializing maxV in the maxArray method, you might want to use the first value of the array (double maxV = dar[0]), because if all doubles in the array are negative, maxV with the number 0 will be the highest. (You could also use the lowest double value possible by saying double maxV = Double.MIN_NORMAL).
1) make your method static
2) Remember in java use BigDecimal class to do any decimal arithmetic.

Printing out a non-variable int in a different method in Java

I am trying to test whether my method to find the number of odd numbers in an array works with a System.out.println() call. I know there are no issues with the array itself, as I've printed it successfully with the toString() call. Here is my method:
public static int ODD(int[] oddnumbers)
{
int countOdds = 0;
for(int i = 0; i < oddnumbers.length; i++)
{
if(oddnumbers[i] % 2 == 1) // check if it's odd
countOdds++; // keep counting
}
return countOdds;
}
And then earlier on in the main method, I called ODD and tested it with System.out.println:
public static void main(String args[])
{
ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + countOdds);
}
Basically the question I have is, how do I get the return countOdds into a variable that I can pass to be printed in System.out.println() in the main method?
Either use a temporary variable to store the returned value and print that, or include the method call in the print statement. For more information, see Returning a Value from a Method.
Just do :
System.out.println("And here are how many odd numbers there are in that array: " + ODD(randomThirty));
Use int countOdds = ODD(randomThirty); in your main method.
Your countOdds variable in your function is local to that function. Variables defined in functions in java are local not global.
You just need to assign the result of the ODD method call to a variable:
public static void main(String args[])
{
int result = ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + result);
}
You will need to store the return result of your call to ODD in a variable, like so:
public static void main(String args[])
{
int countOdds = ODD(randomThirty); // will find how may numbers in the given numbers (from the array) are ODD numbers and return this count to main method.
System.out.println("And here are how many odd numbers there are in that array: " + countOdds);
}
Just save the result like any other variable:
int countOdds = ODD(randomThirty);
public static void main(String args[]) {
int countOdds = ODD(randomThirty);
...
}
To get the returned value you have to pass the argument into the method and call it.
int ans = ODD(randomThirty);
System.out.println(ans);
This is really all you need to do. You can call methods while passing an argument and assign a variable to the returned answer.

Categories