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;
}
}
}
Related
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
I am a new learner of Java. I learned some of the Java core concepts. I got the identifier expected error when run my following code:
class Sekar {
public static int i,j,k;
i = 900;
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
When I compile my code, I get the following error:
error: identifier expected
i = 900;
^
Can any one explain why this error happens here?
When I google about identifier expected error, I found that this error happens when variables are declared without datatype, but I declared that for all my variables i,j,k.
When I redeclare the data type again while setting value to "i" like int i = 900 it works. Why does it?
i = 900;
This is a statement in Java, it can be inside Constructor or method, or initialization block.
In your case, you may move that inside the max() method
When I re declare the data type again while setting value to "i" like
int i = 900 it works. Why does it?
Here, you are declaring and assigning the value to the variable in the same time, same line.
Check here for more details and here about java statements, expressions
Statements
Statements are roughly equivalent to sentences in natural languages. A
statement forms a complete unit of execution. The following types of
expressions can be made into a statement by terminating the expression
with a semicolon (;).
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
Hava a look at Java: Identifier expected :
i = 900;
is a statement as any other. You can't write statement anywhere. It must be in methods/constructors body. Initializing variable in declaration is called definition and is exception to this rule.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
If you want to initialize static variable you can do it 2 (sane) ways:
Initialize variable right where you are declaring it:
class Sekar {
public static int i = 900, j,k;
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
or do it in static constructor:
class Sekar {
public static int i, j,k;
static {
i = 900;
}
static void max()
{
j = 100;
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
Also, if you want to define a constant I recommend using final keyword.
j could be converted to local variable.
class Sekar {
public static final int I = 900;
static void max()
{
int k;
int j = 100;
if(I>j)
{
k=I;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+I+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
What you probably want to do is this:
class Sekar {
public static int i=900,j=100,k;
static void max()
{
if(i>j)
{
k=i;
}
else {
k=j;
}
System.out.println("The maxmimum vale between"+i+"and"+j+"is :"+k);
}
public static void main(String[] args) {
max();
}
}
However I would discourage you from using static fields in this case. I would suggest you to make i, j and k parameters to your method. And give them descriptive names while you're at it.
Also note that k is not initialised explicitly and is therefore set to 0 by default, so your else clause is never reached.
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)
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.
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)