It's a requirement of my school assignment that I use "this" in the following program. However, I can't quite figure out where I could put this. I keep getting a "non-static variable this cannot be referenced from a static context" error.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String args[])
{
System.out.println("Enter the upper limit for the prime numbers computation: ");
int upperLimit = new Scanner(System.in).nextInt();
int count = 0;
for(int number = 2; number<=upperLimit; number++)
{
if(isPrime(number))
{
System.out.println(number);
count++;
}
}
System.out.println("Number of primes generated: " + count);
}
public static boolean isPrime(int number)
{
for(int i=2; i<number; i++)
{
if(number%i == 0)
{
return false;
}
}
return true;
}
}
The Java keyword this refers to the instance of your class that invoked an instance method. A static method is general to its class, and so you cannot reference any instance (non-static) variables from within it. You can only access instance variables like this from within an instance method, that is, a method that is not defined as static.
So, you would need to create an instance method (of which there are none in your class), in order to use this.
This is nothing more than a reference to the object on which the method was called. Static methods on the other hand can operate without any instance of the class even exisiting, therefore they can't have reference to any object. That's why you can't use this in static method. If you really need this, you have to remove static keywords from your functions and use instance variables in those functions anyhow.
public class PrimeNumber
{
public int count = 0;
public int upperLimit;
public static void main(String args[])
{
PrimeNumber pn = new PrimeNumber();
System.out.println("Enter the upper limit for the prime numbers computation: ");
pn.upperLimit = new Scanner(System.in).nextInt();
pn.doCheck();
System.out.println("Number of primes generated: " + pn.count);
}
public void doCheck() {
for (int number = 2; number <= this.upperLimit; number++)
{
if (this.isPrime(number))
{
System.out.println(number);
count++;
}
}
}
public boolean isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
}
Related
I have an assignment that tells me to do the following:
Create a method named IsPrime(), which accepts a positive integer as a parameter. If a number if prime, the method should return true. (A prime number is evenly divisible only by 1 and itself). Incorporate this method into a class named MyMathMethods. Create a main() method in a separate class called MainFile, which will test IsPrime() by asking the user for a number using an input dialog and will then report whether that number is prime or not.
How do I connect these two files?
here is my code:
package x;
import java.util.Scanner;
public class MyMathMethod
{
public static boolean isPrime(int num)
{
int result=0;
System.out.println("enter no");
Scanner s = new Scanner(System.in);
num =s.nextInt();
long sqrt = (int) Math.sqrt(num);
for(long divisor = 2; divisor <= sqrt; divisor++)
{
if(num % divisor == 0)
{
// This only needs to happen once
// for this number to NOT be prime
return false;
}
}
// If we get here, the number is prime.
return true;
}
}
Another File is
import x.*;
package y;
public class MainFile {
public static void main(String [] args) {
boolean isNumberPrime;
int num;
MyMathMethod methods = new MyMathMethod();
isNumberPrime = methods.isPrime(num);
{
if(num=true)
System.out.println(num + " is Prime Number");
else
System.out.println(num + " is not Prime Number");
}
}
}
Thanks in advance.
Do you want to call the method isPrime() from your main in another class?
When they're a in the same package, you have to create a new instance of your class MyMathMethods and call the method isPrime(). when they're in different class, you must import the missing class and do the same as above. If you don't import it manually, probably your IDE will do it for you or ask for it.
the first file:
package x;
public class MyMathMethods {
public boolean isPrime(int number) {
//your code here
return false;
}
}
the second:
package y;
import x.* //importing all files from the package x
//if your class MyMathMethods is in the same package, you don't need that
public class MainFile {
public static void main(String [] args) {
int number = 20;
boolean isNumberPrime;
MyMathMethods methods = new MyMathMethods();
isNumberPrime = methods.isPrime(number); //here the result if it's prime
}
}
EDIT: I'll try to fix your code.
If you want to have your method static, you can call it:
MyMathMethods.isPrime(numer);
without the need to create a new instace.
The next issue: why are you passing to the funtion a variable that is not initialized (num) and try to get this value from the input in this method? Well, that's not a good practise. I would rather suggest to get the input from the user in main (directly in main on in another function called up in main) and then pass the value to isPrime().
package y;
import x.*
public class MainFile {
public static void main(String [] args) {
int num;
Scanner s = new Scanner(System.in);
num =s.nextInt();
if(MyMathMethods.isPrime(num)) {
//if true, your code;
} else {
//false, your code;
}
}
}
package x;
public class MyMathMethod {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Your algoritm failed for many numbers, e.g. 0, 1, 2. Well, for this values it doesn't even returned any value. Please always protect your method against any possible wrong parameters.
Can I pass the return value from a method into the main method then utilize that value in another method? That sounds confusing but let me try to explain it better with some code...
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
Lets say I even instantiate the index in the main method such as
int maxIndex = 0;
I want the first method called to return the value, assign that value to the variable maxIndex then utilize that value for the showObjects method. Thanks for any insight that can be given to a coding novice like myself. Is instantiating the variable in the main method no good? What is the logic behind the JAVAC execution here?? The curriculum covered in my course feels like this is an enormous hole that needs to be filled. Basically, How do I utilize a value returned from a method then implement into another method?
Variables are only containers for a value bound to its type. If a method is returning a type, you can place it's return value in a variable located in another block of code. To provide a very basic example for an easier understanding of how this can work:
private String getString(int number) {
if (number == 2) {
return "Not One";
}
return "One";
}
private void printValue(String number) {
if (number.equals("One")) {
System.out.println("i is 1");
} else {
System.out.println("i is not one");
}
}
public static void main(String[] args) {
int i = 1;
String testNum = getString(i);//returns "One"
printValue(testNum);//output: i is 1
}
With this example in mind,
int maxIndex = findPositionLargestObject(geoList);
showObjects(geoList.get(maxIndex));
is valid.
Unless I'm missing something, assign the result of your function call. I suggest you program to the List interface. Also, if using Java 7+ you could use the diamond operator <> like
List<GeometricObject> geoList = new ArrayList<>(); // <-- diamond operator
// ... populate your List.
int maxIndex = findPositionLargestObject(geoList);
and then yes you can use the variable maxIndex
you can obtain the return value in main method like this,
int maxIndex=findPositionLargestObject(geoList);
Code:
public static void main(String[] args){
ArrayList<GeometricObject> geoList = new ArrayList<GeometricObject>();
int maxIndex=findPositionLargestObject(geoList);
System.out.println("BIGGEST OBJECT AT "+ maxIndex +" AREA =
"+geoList.get(maxIndex).getArea());
showObjects(geoList.get(maxIndex));
}
//METHOD RETRIEVING INT OF ARRAYLIST
private static int findPositionLargestObject(
ArrayList<GeometricObject> geoList) {
int maxIndex = 0;
for (int i = 1; i < geoList.size(); i++) {
// AREA OF I COMPARES MAX INDEX
if (geoList.get(i).getArea() > geoList.get(maxIndex).getArea()) {
maxIndex = i;
}
}
return maxIndex;
}
// METHOD FOR PRINTING SINGLE OBJECT OF ARRAYLIST
private static void showObjects(GeometricObject geometricObject) {
System.out.println(geometricObject.toString());
}
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.
So the first part creates a vector and adds a digit to the 10 slots. Then after this nothing happens, i have no errors in my code but it just stops.. why?
package ovn7;
import java.util.Scanner;
public class ovn7a {
int []vektor;
Scanner scan = new Scanner(System.in);
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
}
public int find(int tal) {
System.out.println("tal");
tal = scan.nextInt();
int i = 0;
while(i<10 && vektor[i] != tal) {
i++;
}
return (i <10) ? i : -1;
}
}
This is your main method:
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
}
That's all your program does - when it hits the closing right brace of the main method, execution ends. If you want it to execute public int find(int tal) as well, you need to include a method call to your main method:
int index = find(5); //for example
Remember, the main method is the only one that is called automatically when executing the program! You'll have to call find yourself inside main.
EDIT: per request, an example of main with the method call included:
public static void main(String []args) {
int []vektor = new int[10];
for(int k=1; k<10; k++){
vektor[k]=0+k;
System.out.println(k);
}
int index = find(5); // <-- this find(5) here is a method call for find!
System.out.println("The method returned a value of " + index + ".");
}
You can replace that "5" with any integer, as the method find accepts an integer as an argument. (as a side note, it doesn't matter which integer you pass to find - it overwrites the argument with a new value anyway)
I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code.
The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.)
The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code.
Thanks in advance for any hints.
import java.util.Scanner;
/**
*
* #author
*/
public class NumberArray2{
public static int[] table() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
int[] tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
return tab;
}
static public void output(int [] tab){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void max(int [] tab){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
//return maxNum;
System.out.println(maxNum);
}
static public void divide(int [] tab){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void average(int [] tab){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int[] inputTable = table();
//int s = table();
System.out.println("Written numbers:");
output(inputTable);
System.out.println("Largest number: ");
max(inputTable);
System.out.println("All numbers that can be divided by three: ");
divide(inputTable);
System.out.println("Average value: ");
average(inputTable);
System.out.println("Prime numbers: ");
isPrime(inputTable);
}
}
Second code
public class Complex {
// datové složky
public double re;
public double im;
// konstruktory
public Complex() {
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public double abs() {
return Math.sqrt(re * re + im * im);
}
public Complex plus(Complex c) {
return new Complex(re + c.re, im + c.im);
}
public Complex minus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public String toString() {
return "[" + re + ", " + im + "]";
}
}
Let's start with a simple example:
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(personA.getFullName());
System.out.println(personB.getFullName());
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public String getFullName()
{
return (lastName + ", " + firstName);
}
}
I am going to make a minor change to the getFullName method now:
public String getFullName()
{
return (this.lastName + ", " + this.firstName);
}
Notice the "this." that I now use.
The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(Person.getFullName(personA));
System.out.println(Person.getFullName(personB));
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public static String getFullName(final Person thisx)
{
return (thisx.lastName + ", " + thisx.firstName);
}
}
So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.
Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.
First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:
Car
properties - engine, gearbox, chasis
methods - ignite, run, brake
The ignite method depends on the engine field.
Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations.
Take a look at java.lang.Math - it's methods are static for that precise reason.
The program below has been coded by making the methods non-static.
import java.util.Scanner;
public class NumberArray2{
private int tab[]; // Now table becomes an instance variable.
// allocation and initilization of the table now happens in the constructor.
public NumberArray2() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
}
public void output(){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
public void max(){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
System.out.println(maxNum);
}
public void divide(){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
public void average(){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public void isPrime() {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// instatiate the class.
NumberArray2 obj = new NumberArray2();
System.out.println("Written numbers:");
obj.output(); // call the methods on the object..no need to pass table anymore.
System.out.println("Largest number: ");
obj.max();
System.out.println("All numbers that can be divided by three: ");
obj.divide();
System.out.println("Average value: ");
obj.average();
System.out.println("Prime numbers: ");
obj.isPrime();
}
}
Changes made:
int tab[] has now been made an
instance variable.
allocation and initialization of the
table happens in the constructor.
Since this must happen for every
instantiated object, it is better to
keep this in a constructor.
The methods need not be called with
table as an argument as all methods
have full access to the instance
variable(table in this case)
The methods have now been made
non-static, so they cannot be called
using the class name, instead we need
to instantiate the class to create an
object and then call the methods on
that object using the obj.method()
syntax.
It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)
Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {
In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.
Before:
NumberArray2.isPrimeNum(11);
After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class
numberarray2.isPrimeNum(11); // Call a method of the given object
In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object).
When you deside to not include a constructor the java compilator will add on for you. It would look like this:
public NumberArray2(){};
Hope this helps. And you are right, this looks like homework :D
I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).
The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.
I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.
Person john = new Person("John",18);
Person alice = new Person("Alice",17);
if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"
static is used when you want to retain a value of something across all objects of the same class.
class Person{
static int amountOfPeopleCreated;
public Person(string name, int age){
amountOfPeopleCreated++;
setName(name);
setAge(age);
}
...
}
so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.