How to call java method on main class - java

I'm a beginner in Java and I have a very simple problem. I'm trying to finish an activity and I forgot how to call a method on the main class.
I keep getting an error whenever I try ways to call the computeSum method on the main class.
Error: Error: Main method not found in class array.Array, please define the main method as: public static void main(String[] args)
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
}
public int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}

Suppose if your class is there in com.arr package. you can specify the qualified name of the class at the time of creating object. Because Array class is already available in java.util package. It is better to create object to your Array class along with package name.
public static void main(String[] args){
com.arr.Array a1 = new com.arr.Array();
int[] numberArray = {1,7,9,0,45,2,89,47,3,-1,90,10,100};
a1.computeSum(numberArray);
}
computeSum() it's an instance method. we have to create Object to your class for calling the instance methods.

You can try this
public class Array{
public static void main(String[] args ){
//Dont know what to put here to call computeSum
int[] nums = {1,2,3,4,5};
int sum=computeSum(nums);
System.out.println(sum);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}

You need to create an instance to invoke member method of a class.
public static void main(String[] args ){
Array myArray = new Array();
int[] values = new int[] {1,2,3,4};
myArray.computeSum(values);
}

You can read about instance methods and static methods.
computeSum() is an instance method, which means it would need an object of Class Array to be called, example:
public static void main(String[] args){
Array array = new Array();
int[] nums = {1,2,3};
array.computeSum(nums);
}
Alternatively, you could make it a static method to use it without making an object, which is not recommended, but incase you want, this is how you can do it:
public class Array{
public static void main(String[] args ){
int[] nums = {1,2,3};
int sum = computeSum(nums);
}
public static int computeSum(int[] nums){
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
}

First you need to understand the difference between static classes/members and instance classes/members.
Your main method is static - as is standard for the entry method of a program - meaning it is available immediately without any binding to an instance of the Array object.
Your computeSum method is an instance method. Meaning that you need an instance of the object Array, to use it, and it will execute in that object's context.
Your choices:
1)
Make computeSum static:
public static void main(String[] args) {
computeSum({1,2,3}); // or Array.computeSum() outside of Array
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
2)
Make an instance of the Array object:
public static void main(String[] args){
Array myArray = new Array();
myArray().computeSum({1,2,3});
}
public static int computeSum (int[] nums) {
int sum = 0;
for (int i=0; i<nums.length; i++){
sum= sum+nums[i];
}
return sum;
}
Static code - not ran in the context of an object's instance - can not reference members that are not static, this makes sense as, how would it know what object instance of that member you are referencing (myArray1.computeSum()? or myArray2.computeSum()? It doesn't even know these two instances of the myArray object exist).
Hope this helps. :)

Or you could use reflection just for a change ;)
https://docs.oracle.com/javase/tutorial/reflect/

Firstly your method have an attribute which is "int[] nums " to call the method you need to set a value to your attribute .
NOTE that you don't have to give the same name to your attribute while calling.
for example : 1 - int[] Myattribute = {1,2,3};
int sum = computeSum(Myattribute );
put this line incide your Main it ill work

Related

What is the best way to called non-static method from static method in java?

I know there are a lot of questions about this topic.
I have two procedures to call arrPrint method.
1st Procedure:
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
Test test = new Test();
test.arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
2nd Procedure :
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
arrPrint(arr);
}
public static void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
Which procedure is best and why?
Instance methods run on instances of a class, so to execute an instance method you need an instance of a class. Therefore, if you want to call an instance method from within a static method, you need some access to an instance, either a global variable or passed as argument. Otherwise, you will get a compilation error.
2nd procedure is used if you want to use the method arrPrint in another class.
public class A{
public int[] intArray;
public A(int[] intArray) {
this.intArray = intArray;
}
public int[] getIntArray() {
return intArray;
}
}
public class Pourtest {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
A a = new A(arr);
arrPrint(a.getIntArray());
}
public static void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)System.out.println(arr[i]);
}
}
"Instance method" means the method needs to be executed on an instance of the class. The point of objects is that instances can have their own dedicated data, which the instance methods act on, so trying to call an instance method without an object instance doesn't make sense. If you rewrite your example to:
public class Test {
int[] arr = new int[] {1,2,3,4,5};
public static void main(String args[]) {
Test test = new Test();
test.arrPrint();
}
public void arrPrint() {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
then this becomes a little simpler. The instance of Test has its own data, which the instance method can access and do something with.
Look at JDK classes like String or ArrayList and see how they're designed. They encapsulate data and allow it to be accessed through instance methods.
On the other hand static methods can't see instance data, because they don't belong to an object instance. If an instance method doesn't touch any instance data, some static analysis tools like sonarqube will recommend that the instance method be changed to a static method. Since your method operates on data that is passed in and the object created to call it as an instance method is unnecessary, it's better for it to be a static method.

why i canĀ“t acces to makeRange method

I just started with java and I create a class Range() inside my superclass with a method inside makeRange but when I tried to access to that method throws an error. Whats wrong here?
Here is my code...
public class iAmRichard {
class Range{
int[] makeRange(int upper, int lower){
int[] ary = new int[(upper - lower)+1];
for(int i = 0; i > ary.length; i++ ){
ary[i] = lower++;
}
return ary;
}
}
public static void main(String[] args) {
int foo[];
Range fui = new Range();
foo = Range.(here do not apear makeRange method)
You're creating an inner class here called Range. I don't believe that's what you intended to do, but I'll answer it as stated.
You're referring to this class in a static context, and the inner class can't be referenced with a static context. To address that, you need to make the change to Range: make it static.
public class iAmRichard {
static class Range {
}
}
Further, you're already getting an instance of Range, so all you need to do is use it.
foo = fui.makeRange(1, 10);
If you elected to only create a class called Range, you wouldn't have to deal with any inner classes at all, which I think would be the cleaner approach here.
public class Range {
int[] makeRange(int upper, int lower) {
int[] ary = new int[(upper - lower) + 1];
for (int i = 0; i > ary.length; i++) {
ary[i] = lower++;
}
return ary;
}
public static void main(String[] args) {
int foo[];
Range fui = new Range();
foo = fui.makeRange(1, 10);
}
}
To access a method without creating an instance you have to declare it static. In your case you have also to declare the class Range as static.
Or you can just use the instance you already have with a few changes:
iAmRichard richard=new iAmRichard();
Range fui=richard.new Range();
foo = fui.makeRange(...);
Note tha you need an instance of iAmRichard to create a Range.
Since the call is made from a static block in a static way(No instance is used for calling makeRange method) we need to have the called method to be either static or we need the object of the class to call instance methods.
statically you can use this example to access your method. Here is a link for more information on static methods.
public class IAmRichard {
public static void main(String[] args) {
int foo[];
foo = Range.makeRange(10,1);
}
static class Range{
static int[] makeRange(int upper, int lower){
int[] ary = new int[(upper - lower)+1];
for(int i = 0; i > ary.length; i++ ){
ary[i] = lower++;
}
return ary;
}
}
}

printing method class randTest (int n)

I am having trouble printing out the method randTest (int n) as errors keep appearing. I want to print this method in the main as i want to print the results in a clear tabular form. The method must stay static void. This is my code below:
public class RandNumGenerator {
public static int RandInt(){
double n = Math.random()*10;
return (int) n;
}
public static void randTest(int n){
int [] counts = new int [10];
for(int i=0;i<n;i++){
counts[i] = RandInt();
System.out.println(counts[i]);
}
}
public static void main(String[] args) {
System.out.println(RandInt());
System.out.println(randTest());
}
}
Just call the method randTest() instead of printing it. The work of printing is already done inside the method. And randTest takes in an argument of the type int. So, you need to save the return of RandInt and then pass it into the method.
public static void main(String[] args) {
int randInt = RandInt();
System.out.println(randInt);
randTest(randInt);
}

How to use main array in method?

I want to take user input for merge sorting so i'm using the array ar[] in the method but it gives error "cannot find symbol " for ar[]..
import java.util.*;
import java.io.*;
class Test
{
int Merge()
{
int q,p,r,i,l,m,j,t,k,w,x,s,u;
w=q-p+1;
x=r-q;
int[] L=new int [w+1];
int b=1;
for(s=1;s<=w+1;s++)
{
L[b]=s;
b++;
}
int[] R=new int [x+1];
int c=1;
for(t=1;u<=x+1;u++)
{
R[c]=u;
c++;
}
for(i=1;i<=w;i++)
{
L[i]=ar[p+i-1];
}
for(j=1;j<=x;j++)
{
R[j]=ar[q+j];
}
L[w+1]=1000;
R[x+1]=1001;
i=1;
j=1;
for(k=p;k<=r;k++)
{
if(L[i]<=R[j])
{
ar[k]=L[i];
i=i+1;
}
else
{
ar[k]=R[j];
j=j+1;
}
}
System.out.println("sorted array"+ar[k]);
}
public static void main(String ar[])
{
int a0=Integer.parseInt (ar[0]);
int a1=Integer.parseInt (ar[1]);
int a2=Integer.parseInt (ar[2]);
int a3=Integer.parseInt (ar[3]);
int a4=Integer.parseInt (ar[4]);
int a5=Integer.parseInt (ar[5]);
int a6=Integer.parseInt (ar[6]);
int a7=Integer.parseInt (ar[7]);
int a8=Integer.parseInt (ar[8]);
int a9=Integer.parseInt (ar[9]);
int p=a0,r=a9,q;
if(p<r)
q=(p+r)/2;
Test T=new Test();
T.Merge();
}
}
ar is visible only in the scope of main method, it's unknown in other methods. In order to see it in other methods, you need to have a class member that will hold its value.
You have an ar local variable in the main method, but you don't have it in the Merge method. Local variables, and method parameter is just another kind of local variable, are... well, local to the method where they are declared. That means that such a variable is undefined in another method.
For example, you can have
class Test {
final int[] ar;
Test(int[] ar) { this.ar = ar; }
public static void main(String[] ar) {
....
final Test t = new Test(ar);
t.Merge();
}
}
ar is will be visible in main method only, you need to create a new array in main method. Copy values read into new array and pass this array as input to merge method.

Java - Change values of an array by a method in a Class

Here is my code:
class Myclass {
private static int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
int[] array = new int[10];
}
}
It throws a java.lang.nullPointerException when trying to do this:
m.array[i] = i;
Can anybody help me please?
You have declared a local variable array in your constructor, so you're not actually initializing the array declared in Myclass.
You'll want to refer directly to array in the constructor. Instead of
int[] array = new int[10];
Use this
array = new int[10];
Additionally, you've declared array static in the scope of your Myclass class.
private static int[] array;
You only have one instance of Myclass here, so it doesn't matter, but normally this would not be static, if you're initializing it in a constructor. You should remove static:
private int[] array;
In your constructor you are making your assignment to a local variable names array, not the static class variable also named array. This is a scope problem.
I'm also guessing that since you access array via m.array, you want a member variable and not a static one. Here's the fix
class Myclass {
private int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
rray = new int[10];
}
}
in MyClass() type this
this.array = new int [10];
instead of this
int[] array = new int[10];
Your code should be as below. In the constructor, instead of initializing the instance variable you created a new local variable and the instance variable was left uninitalized which caused the NullPointerException. Also the instance variable shouldn't be static.
class Myclass {
private int[] array;
public static void main(String[] args) {
Myclass m = new Myclass();
for (int i = 0; i < 10; i++) {
m.array[i] = i;
System.out.println(m.array[i]);
}
}
public Myclass() {
array = new int[10];
}
}
First, if you plan to use array as a field of m (i.e. m.array) don't declare it as static, but:
private int[] array;
Next thing you have to do is to initialize it. Best place to do that is in the constructor:
public MyClass() {
array= new int[10]; //just array = new int[10]; don't put int[] in front of the array, because the variable already exists as a field.
}
The rest of the code should work.

Categories