How to call a static method from main class? - java

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())

Related

How to initialize an array in the constructor?

Lets say we have these two different constructors.
What is the different between the first one and the second one.
How is the way to do it? Explain the difference please!
(I know you cant have these two constructors in the same class, this is just to show what i mean.
public class StackOverFlow {
private int[] x; // instance variable
StackOverFlow(int[] x) { // constructor
this.x=x;
}
StackOverFlow(int[] x) { // constructor
this.x = new int[x.length];
for(int k=0 ; k < x.length; k++) {
this.x[k]=x[k];
}
}
The first constructor assigns a reference of an existing int array to the member variable. The caller of the constructor can later change the array and the change would be reflected in the instance.
The second constructor copies the array, so later changes in the passed array wouldn't change the copy stored in the instance.
int[] intArray = new intArray {1,2,3};
StackOverFlow so1 = new StackOverFlow(intArray); // assume we are using the first constructor
intArray[1]=5; // changes the array stored in `so1` object
StackOverFlow so2 = new StackOverFlow(intArray); // assume we are using the second constructor
intArray[1]=8; // doesn't change the array stored in `so2` object
In the first case you tell your instance variable to refer to the given x, so when you change data in one of these variables, that changes also affect the second variable.
And in the second case you create a copy of an object, so your instance variable and variable you pass to constructor will need independent from each other in your further code.
This will not work since you got an ambiguity issue as both constructors receive the same type of parameters. So when you try to create an instance :
StackOverflow instance = new StackOverflow(new int[]{});
There is no way to know which constructor should be called.
You need to decide which behavior is good for you.
I would recommend using the second constructor and create a setter method if you want to set the array from an initialized one :
public class StackOverFlow {
private int[] x; // instance variable
StackOverFlow(int[] x) { // conctructor
this.x = new int[x.length];
for(int k=0 ; k < x.length; k++) {
this.x[k]=x[k];
}
}
public void setTheArray(int[] x) {
this.x = x;
}
}

Trouble understanding this findMinimum array method

So I'm sorting arrays in subclasses that inherit a couple of methods from a class with things like swap to switch indexes a method to find the minimum value, method to print etc, however for the findMinimum method, my teacher provided us with a pre-made code, but I'm having a little trouble understanding it, was hoping some of you would be able to help.
An array is inserted by the user in a main class
public int findMinimum(int[] array, int first){
int minIndex = first;
for(int i =0; i<array.length; i++){
if(array[i]<array[minIndex]){
minIndex = i;
}
}
return minIndex;
}
What I'm having a hard time understanding is since int first is given no initial value isn't it considered null and therefore can't be used to check in the loop? How can int minIndex be set equal to null?
Thanks in advance
int first is a function parameter, so it will have an initial value when you call this function. You will call it with some array and initial assumed index of min:
myMinimum = findMinimum(myArray, 0)
In this case it actually doesn't make much sense, because minimum of a function will not depend on this parameter. I'd rewrite it as:
public int findMinimum(int[] array){
int minIndex = 0;
for(int i = 1; i < array.length; i++){
if(array[i] < array[minIndex]){
minIndex = i;
}
}
return minIndex;
}
See, I also skip the very first value because it is an initial minimum by default.
When you call this method in your code, you supply an initial value for both array and first, such as this...
public static void main(String[] args){
int[] myArray = new int[]{2,5,10,30};
int theMinimum = findMinimum(myArray,5);
}
The variable first will always have a value, it just depends on what is passed through by the method call. In the example above, the value of first is 5.
Maybe this is where you're getting confused... Your code is a method - it only gets run when you call the method in your code, as in the above example. If you don't call the method findMinimum(), then this code will never be run. The exception to this is your main() method, which is a special method that is understood my the Java JVM as being the entry point, the first bit of code that is run. All other methods need to be called, and passing through the values it requires (in this case, passing through values for array and first)

Setting all values of a 2d array (java)

I am trying to fill a 7x6 blank 2d Array in java with a value of -1.
I initialized the array in a non-main class by typing:
int[][] anArray = new int[7][6];
Then I created a method setArray() which looks like the following:
public int[][] setArray()
{
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 6 ; j++)
{
anArray[i][j] = -1;
}
}
return anArray;
}
but when I run this method through the main class, it returns the board as:
[[I#71988d36
Does anyone know why this is happening? I'm fairly sure the above code is correct.
edit: Forgot a pair of curly braces.
Every class extending Object in Java (that is, all of them) inherits this method:
public String toString()
Which is called when you invoke to decide what to actually print
System.out.println()
The problem is, unless you override it, it will return something not very helpful which will get printed (except in a few cases such as String, int ....).
In this particular case, rather than overriding it, and as the comments above explain, it's easier to call a wrapper function that takes the array as a parameter and delivers a nice String as a result.

Adding numbers to arrays with methods in another class?

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);
}

How to use a value returned in a different class?

This is probably a very simple question. Say I had a class that computed the gcd, called Gcdcomp. The code in that class all works. When i refer to it in my main block of code, I say..
Gcdcomp.getGcd(a, hii);
a and hii are my two variables. By default, the Getgcd class uses int a and int b and will return a after executing euclids algorithm. How do I use that returned value as a variable in my main code?
You can assign the result of a function call directly to a variable, like this (assuming that getGcd returns an int):
int result = Gcdcomp.getGcd(a, hii);
Or if result is already declared beforehand, you can omit the declaration, like this:
result = Gcdcomp.getGcd(a, hii);
int gcd = Gcdcomp.getGcd(a, hii);
This is the pattern for using methods:
int myMethod(int x) {
int y = x * 3;
return y;
}
...
int z = myMethod(57);
You'd have to write a get method that would return that value.

Categories