non-static method compute(int) cannot be referenced from a static context - java

The code given below is giving the following error:- non-static method compute(int) cannot be referenced from a static context
If i cannot create a method inside main(), what should i do.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner key = new Scanner(System.in);
int t = key.nextInt();
for(int i=0;i<t;i++){
int a = key.nextInt();
int b = key.nextInt();
a=compute(a);
b=compute(b);
System.out.println(a+b);
}
}
int compute(int a){
int basea=0, digit;
int temp=a;
while(temp>0){
digit = temp%10;
temp/=10;
if(digit>(basea-1))basea=digit+1;
}
temp=a;
a=0;
int count=0;
while(temp>0){
digit = temp%10;
temp/=10;
a+=digit*Math.pow(basea,count);
count++;
}
return a;
}

You have two options:
Declare compute() static:
static int compute(int a){
Create an instance of IdeOne and call compute() via that reference:
IdeOne ideOne = new IdeOne();
a = ideOne.compute(a);
I think it would be a good idea to read through the Java tutorials on classes and objects.

You're trying to call a non-static method (which is compute) from a static method (the main).
Change int compute(int a){ with static int compute(int a){

In your case make method compute static. Otherwise create an Ideone object and call your method on it.

You can not access non-static method from static method.
Method you are trying access is instance level method, you can not access instance method/variable without class instance.
You can't access something that doesn't exist. By default non-static method doesn't exist yet, until you create object of that class in which method exist. A static method always exists.
You can access your method by following way :
1. Make your compute() method static
int compute(int a){
///rest of your code
}
2. Create instance of your class Ideone and access method by class object.
IdeOne obj = new IdeOne();
obj.compute(a);
obj.compute(b);

The answers given here are mainly to make the method static, which is fine for a program this size. However, as projects get bigger not everything will be in your main anymore, and thus you get this static/non-static issue on a larger scale as your other classes won't be static.
The solution then becomes to make a class for your Main, as such:
public class Main {
public static void main( String[] args ) {
Ideone ideone = new Ideone();
Then another file which houses your class Ideone:
public class Ideone {
Scanner key;
public Ideone() {
key = new Scanner(System.in);
int t = key.nextInt();
for(int i=0;i<t;i++){
int a = key.nextInt();
int b = key.nextInt();
a=compute(a);
b=compute(b);
System.out.println(a+b);
} // end constructor
int compute(int a){
int basea=0, digit;
int temp=a;
while(temp>0){
digit = temp%10;
temp/=10;
if(digit>(basea-1))basea=digit+1;
}
temp=a;
a=0;
int count=0;
while(temp>0){
digit = temp%10;
temp/=10;
a+=digit*Math.pow(basea,count);
count++;
}
return a;
} // end compute
} // end class
As for your main file. What I do will work, but better practice is to follow the code example given here:
http://docs.oracle.com/javase/tutorial/uiswing/painting/step1.html
Applying this practice will ensure that you do not have static/non-static issues anywhere in your project, as the only thing that is static is the initialization of your actual code, which then handles all codes / further initilization of other classes (which is all non-static)

Related

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

How to call java method on main class

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

How to instantiate a new public Java class if a parameter is required?

I need an array to be public (accessible to other methods in the class) but the array needs an input value "T" to create it. How do I instantiate a "global" variable that requires user input?
My code is as follows:
public class PercolationStats {
**private double myarray[];**
public PercolationStats(int N, int T) {
**double myarray = new double[T];**
for (i=0;i<T;i++) {
Percolation percExperiment as new Percolation(N);
//do more stuff, make calls to percExperiment.publicmethods
myarray[i] = percExperiment.returnvalue;
}
}
public static void main(String[] args) {
int N = StdIn.readInt();
int T = StdIn.readInt();
PercolationStats percstats = new PercolationStats(N, T);
//do more stuff, including finding mean and stddev of myarray[]
StdOut.println(output);
}
Another example in pseudocode:
class PercolationStats {
Constructor(N, T) {
new Percolation(N) //x"T" times
}
Main {
new PercolationStats(N, T) //call constructor
}
}
class Percolation {
Constructor(N) {
**new WQF(N)** //another class that creates an array with size dependent on N
}
Main {
**make calls to WQF.publicmethods**
}
}
In the second example, it seems to me that I need to have the new instance of class WQF made in the constructor of the Percolation in order to accept the parameter N. However, WQF would not be accessible to the Main method of Percolation.
Help!
Don't include the type declaration in your constructor. You are creating a local variable that masks the field. It should look like this:
public class PercolationStats {
public double myarray[];
public PercolationStats(int n, int y) {
myarray = new double[t];
for (i=0; i<t; i++) {
Percolation percExperiment = new Percolation(n);
//do more stuff, make calls to percExperiment.publicmethods
myarray[i] = percExperiment.returnvalue;
}
}
public static void main(String[] args) {
int n = StdIn.readInt();
int t = StdIn.readInt();
PercolationStats percstats = new PercolationStats(n, t);
//do more stuff, including finding mean and stddev of myarray[]
StdOut.println(output);
}
}
There's certainly no problem using a variable as the length when creating a new array.
Tedd Hopp's answer corrects the bug in your code.
I'd just like to point out that myarray is NOT a global variable.
Java doesn't have global variables,
the closest it has is static variables, and
myarray isn't one of those either. It is an instance variable, as you have declared it.
(And an instance variable is the right way to implement this ... IMO)

static method and non static method Java

I know I'm doing something stupid, but I cannot figure how to fix it.
The issue is inside the private method removeVowels particulry when using the vowels method.
The compiler gives
non-static variable vowels cannot be referenced from a static context
Here is my code:
public class RecursionHW2 {
String vowels;
// Part (A) First way
public static int upperCase(String myString){
return upperCaseChecker(myString , 0 );
}
public static int upperCaseChecker(String myString, int index){
int inc;
//My Base Code
if(myString.length() <= index) return 0;
if(Character.isUpperCase(myString.charAt(index)) == true) inc= 1;
else inc= 0;
return inc+upperCaseChecker(myString,index+1);
}
// First way of Solving part (B)
public static int count(String str, char a)
{
if (str.length() == 0)
return 0;
else if (str.charAt(0) == a)
return 1 + count(str.substring(1, str.length()), a);
else
return count(str.substring(1, str.length()), a);
}
//Second way of solving part (B)
public static int anotherCount(String myString, char myWord)
{
return anotherCount(myString, myWord, 0);
}
public static int anotherCount(String myString, char myWord, int index)
{
int inc;
if (index >= myString.length())
{
return 0;
}
if (myString.charAt(index) == myWord) inc =1;
else
inc = 0;
return inc + anotherCount(myString, myWord, index+1);
}
// part (C) solving
public Boolean isSorted(int[] a, int n)
{
if(n == 0 || n == 1) return true;
else
return isSorted(a, n, 1);
}
private Boolean isSorted(int[] a, int n, int cur)
{
if(cur == n) return true;
if(a[cur - 1] <= a[cur])
return isSorted(a, n, cur+1);
else
return false;
}
//part (D) Solving
public static String removeVowels(String myString)
{
return removeVowels(myString, "");
}
private static String removeVowels(String myString, String t)
{
if(myString.length() == 0) return t;
if(vowels.contains(myString.charAt(0) + ""))
return removeVowels(myString.substring(1), t);
else
return removeVowels(myString.substring(1), t + myString.charAt(0));
}
public static void main(String[] args){
//I've wrote 2 ways to solve the Second Recursive Q2
System.out.println("Method 1: Number of Occurence " + count("Hello This is Mohammad Fadin",'o'));
// System.out.println("Method 2: Number of Occurence "+ anotherCount("Hello This is Mohammad Fadin",'o'));
String s1 = "Hello WorlDD";
System.out.println("Number of Upper Cases " + upperCase(s1));
String s2 = "Hello";
System.out.println("After Vowels Removed " + removeVowels(s2));
}
}
You've "infected" your code with static from your main method. In your main method you should do something like this, so you don't have to make everything static:
public class RecursionHW2
{
public static void main(String[] args)
{
RecursionHW2 rhw2 = new RecursionHW2();
int count = rhw2.count("Hello world");
// and so on
}
}
You cannot reference an instance variable from a static context. You have to create an instance of RecursionHW2 first, or make the variable vowels static which makes more sense. Or you might consider to remove static modifier from removeVowels method.
Update:
However, your class looks like a bunch of utility methods, so you may want to make it non-instantiable (by adding a private constructor), make all of your methods static (because they clearly don't operate on object's state) and pass vowels as an additional parameter to removeVowels method.
The problem is exactly what the compiler tells you: you are referencing a non-static (instance) variable vowels from a static context. Actually, almost all your methods are static which is an extremely bad design.
Make all methods which require access to instance data (here: vowels instance variable) non-static and instantiate your class in main().
Change:
String vowels;
to:
static String vowels;
You cannot use String vowels inside your static methods because vowels is non-static. You need to add static keyword to the string, then your code will work.
you can make the variables static or just keep everything non-static and this will get solved. The bigger question you need to ask your self is when should i use static and when not ?
change
String vowels;
to
static String vowels;
All your methods are static and thus do not require an instance of your object to be present - ie you don't have to say
x = new RecursionHW2();
x.upperCase(..);
However if you don't make vowels static, it doesn't exist unless an object is instantiated.
Static variables belong to the class, the static variables that are not belong to the class instances (objects).
Test
class Foo {
private static String vowers;
private String bar;
}
Foo a = new Foo ()
Are creating a new instance of class Foo, each instance has its own variable bar, but all share vowers variable because this belongs to the class. Same goes with the static methods.
Within a static method (class method) you can not reference variables that are not static. Why is this so?
imagine that from a static method you reference a variable that is not static
class Foo {
private static String vowers;
private String bar;
public static void exampleMethod () {
bar = "home";
}
}
If you do this:
Foo a = new Foo () / / has a new bar
Foo b = new Foo () / / has a new bar
vowers is a single variable and belongs to the class not the instance
When you
Foo.exampleMethod()
The method does not know that variable bar used if the variable of instance a or the variable instance of b. Therefore you can only access static variables of the class from a static method

Fibonacci Sequence return argument

I need to generate a program that generates the Fibonacci Sequence
Here is what I have so far:
import java.util.Scanner;
public class FibonacciRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter n:");
int n = in.nextInt();
EP64 fg = new EP64();
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber());
}
}
public class EP64
{
public static void nextNumber(int n)
{
int fold1 = 1;
int fold2 = 1;
int fnew = fold1 + fold2;
fold1 = fnew;
}
}
I get an error on:
System.out.println(fg.nextNumber());
saying:
method nextNumber in class EP64 cannot be applied to given types:
required: int
found: no arguments
reason: actual and formal argument lists differ in length
and can someone also tell me if I am doing this program right? If not, help! I looked at other similar questions but I cannot make much sense of them
Thank you all!
method nextNumber in class EP64 cannot be applied to given types: required: int found: no arguments reason: actual and formal argument lists differ in length
Your
public static void nextNumber(int n)
^^^^^^^
says that any call to the method must provide an integer as argument. But here:
System.out.println(fg.nextNumber());
^^ you need to add an integer argument
you violate this by providing no argument.
As your code reads now, I'd probably drop the int n argument.
and can someone also tell me if I am doing this program right?
Naah, not really...
fold1 and fold2 should probably be member variables (so they don't get reset in every call to the method),
You're forgetting to update fold2 (you only update fold1),
Also, you probably want to return an int from the nextNumber method.
Read up on
Official Java Tutorial: Defining Methods
You are calling a static method to a object reference instead of the class itself.
And
Not passing any argument at all for nextNumber() method.
Make the method non-static as :
public void nextNumber(int n) {}
Pass arg to the method as :
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber(n));
And also don't forget to return the processed number from your nextNumber method,which you collecting in System.out.println.
Your declaration of nextNumber says it takes an int argument, but you are calling it with no arguments.
Also, your code isn't going to do what you want. You probably should make fold1 and fold2 members of class EP64 and make the method an instance method rather than a static method. You also need to do fold2 = fold1; before you update fold1.
Finally, you need to declare nextNumber to return an int value, and then actually have it return an int value.
You have two problems. Firstly, your method doesn't return anything, i.e. it is void. You need to make it int and add a return fnew; at the end. The other problem is you are starting from scratch every time, it will return 2 each time. You need to make fold1 and fold2 fields by moving them above the nextNumber line. Oh, and drop the int n argument as it doesn't do anything.
I agree on the diagnostics of the other posts, but don't suggest a member variable, but a rename and local variables.
You can ask for the 5th Fibonacci-Number with 5 calls to
fib.next ();
or with a single call to
fib (5);
Since the fibonacci-sequence increases very rapidly, you have very few calls (54) before hitting the overflow boundary. So if you repeatedly recalc the same sequence, to print the sequence, it's not a big problem. A recursive solution would be fine.
Btw.: EP64 is a very bad name.
I think this is enough:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
int a=0,b=1,c;
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
If you want to call this as a method then:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
callFibonocci(n);
}
public static void callFibonocci(int n)
{
int a=0,b=1,c;
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
You can call this method out of the class;
// Fibnocci Using c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeProject
{
class FibnocciSeries
{
public int[] FibonacciArray(int length)
{
int[] fseries = new int[length];
fseries[0] = 0;
fseries[1] = 1;
if (length == 0)
return null;
//Iterating through the loup to add adjacent numbers and create the memeber of series
for (int i = 2; i < length; i++)
{
fseries[i] = fseries[i - 1] + fseries[i - 2];
}
return fseries;
}
}
}
////////////////////
class Program
{
static void Main(string[] args)
{
FibnocciSeries fb = new FibnocciSeries();
Console.WriteLine("Please Enter Integer Length of Fibnocci series");
int length = Convert.ToInt32(Console.ReadLine());
int[] result = fb.FibonacciArray(length);
foreach(int i in result)
Console.Write(i.ToString()+ " ");
Console.ReadLine();
}
}
|

Categories