Can't access functions in another class - java

****EDIT** For everyone saying call it like
FunctionTestTest.numberCheck(userNumber);
I have tried that numerous times before posting on here it didnt work.
People downvote a question that they cant even answer, great...
On another project Im working on I couldn't call functions from another class. Been trying to fix it all day. Decided to throw up a a few lines of code & try call a function from another class just to make sure i didn't have an unnoticed syntax error in my main project.
can anyone see what the problem is here?
returning this error:
cannot find the symbol
symbol: class FunctionTestTest
location: class FunctionTest
...
public class FunctionTest{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int userNumber = 0;
System.out.println("Please enter a number between 1 - 10");
userNumber = input.nextInt();
FunctionTestTest ft = new FunctionTestTest();
FunctionTestTest.numberCheck(userNumber);
}
}
and..
public class FunctionTestTest{
public static void main(String[] args){
}
public static void numberCheck(int num){
if (num == 1){
System.out.println("function works");
}
}
}

The error is caused because you are probably using class from another package. In this case you have to import it first before using.
If you are using any IDE there should be a hotkey to fixing your problem.
Also...
You don't need to create an object instance to access static methods of certain class. Simply use:
FunctionTestTest.numberCheck(userNumber);
It is not recommended, but you can call a static method on object instance like:
new FunctionTestTest().numberCheck(userNumber);

here you are calling other class constructor and is not present there:
FunctionTestTest ft = new FunctionTestTest(userNumber);
also check if FunctionTestTest class present is some other package then import it

ft.(userNumber);
Your method invocation is incorrect.
Your probably wanted ft.numberCheck(userNumber) or FunctionTestTest.numberCheck(userNumber). The latter is preferred as you are incoking a static member.
If is it a static method, you just call it as:
ClassName.methodName();
There is no need to instantiate an object to use a static method like what you did.
Example:
public class MyClass{
public static void myMethod(){
//do whatever..
}
}
public class OtherClass{
public static void main(String[] args){
MyClass.myMethod(); //invoke a static method from another class
}
}

Related

Error: Main method not found in class singleInheritance.A, please define the main method as: public static void main(String[] args) or a JavaFX

Please solve this problem.I've Spend 5 hours to solve this problem, but I could't.
I'm very thankful to you.Dear I was watching Java tutorial and in that particular video Instructor was writting his code in that case,That I've shown in my question,also there was no public class in his code.but he was writting code in notepad++, here is the screenshot, and my program is here
package singleInheritance;
public class A {
void showA() {
System.out.println(" a class method ");
}
}
class B extends A{
void showB() {
System.out.println(" b class method ");
}
public static void main(String[] args) {
A ob1=new A();
ob1.showA();
}
}
If both A and B are in the same source file (probably A.java), the main method should be in class A, since that's the public class of that file.
If you want the main method to stay in class B, make B public, and put it in its own source file (B.java).
I think you have wrong params of running the app. Check the config and look at the Main class in it. Check that it points to singleInheritance.B rather than singleInheritance.A In IDEA it looks like that:

Using methods from another class in the main?

Okay so I did search this question and a decent amount of results showed up. All of them seemed to have pretty different scenarios though and the solutions were different for each one so I'm a bit confused.
Basically, I have a Driver class that runs my program and contains the main method. I have a second class that has a few methods for editing a party (like party of characters in a game). What I wanted to do was this (part of main method)
System.out.println("Are you <ready> for your next battle? Or do you want to <edit> your party?");
Scanner readyScanner = new Scanner(System.in);
String readyString = readyScanner.next();
while(!readyString.equals("ready") && !readyString.equals("edit")) {
System.out.println("Error: Please input <ready> if you are ready for your next battle, or <edit> to change your party.");
readyScanner = new Scanner(System.in);
readyString = readyScanner.next();
}
if(readyString.equals("edit")) {
displayEditParty(playerParty, tempEnemy);
}
A lot of this is just some background code, the problem lies with
displayEditParty(playerParty, tempEnemy);
I get the error
Driver.java:283: cannot find symbol
symbol : method
displayEditParty(java.util.ArrayList<Character>,java.util.ArrayList<Character>)
location: class Driver
displayEditParty(playerParty, tempEnemy);
So, how could I call this method from another class in my main? In my code I use methods from other classes a few times, I'm a bit confused as to this one doesn't work.
You should make displayEditParty function public static and then you can use it in other class by className.displayEditParty(?,?);
Methods of class can be accessible by that class's object only. Check below code:
class A{
void methodA(){
//Some logic
}
public static void methodB(){
//Some logic
}
}
public static void main(String args[]){
A obj = new A();
obj.methodA(); // You can use methodA using Object only.
A.methodB(); // Whereas static method can be accessed by object as well as
obj.methodB(); // class name.
}
If your method is a static, you can call ClassName.methodName(arguments);
If your driver class not a static one you should create an instant of that class and call your method.
ClassName className=new ClassName();
className.displayEditParty(playerParty, tempEnemy);
I dont see where your declaring the Driver class in your code.
Driver foo = new Driver();
foo.displayEditParty(playerParty, tempEnemy);

I have trouble with static main method and inputting non-static values [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
I am working on a school project, building a Chess-game. I have my board which creates the arrays and fill the board with pieces.
Now, I want to instantiate a new board in a game class and use the console to input player moves. To make this as simple as possible, my trouble is inputting non-static variables.
For instance:
public class Test extends ConsoleProgram{
public static double a1;
public static void main(String[] args) {
a1 = readLine("Insert value of a1");
System.out.println(a1);
}
}
more info on readLine() here
As you probably see, this won't work as java is complaining cannot make static reference to the non-static method readLine()
How do I work around this? Maybe there is something really basic I just don't understand..
As always, thank you very much for your quick and insightful answers!
If you don't want to make your readLine method static, do a call on an instance:
public static void main(String[] args) {
Test me = new Test();
a1 = me.readLine("Insert value of a1");
System.out.println(a1);
}
either define readline as static or
make an object of class and then call the method, new Test().readline();
Make readLine()` as static.Then you can access
If you make method as static then you can use that in main() method
otherwise create an object for Test class then use it
The simplest work around I've found is simply instantiate the object in the main method, and call the relevant methods from the constructor.
public static void main(String[] args)
{
new ClassThing();
}
public ClassThing()
{
// Make your method calls here.
}
This means you can access instance methods, and you don't need to call everything from a static context.
Create Test instance in main and call it's instance method.
public class Test extends ConsoleProgram {
public double a1;
public void run() {
a1 = readLine("Insert value of a1");
System.out.println(a1);
}
public static void main(String[] args) {
Test main = new Test();
main.run();
}
}
You should instantiate an object of the class that has the method readLine().
If that class' name is i.e. Reader you should do something like:
Reader r= new Reader();
a1 = r.readLine("Insert...");`

How to use constructors in Java?

//Vehicle.java
import java.util.Random;
class VehicleConstructor{
private int speed;
private int timeDriven;
private int run;
private int startSpeed; //Pradinis greitis
public VehicleConstructor() {
setSpeed();
System.out.println("Vehicle");
}
private void setSpeed(){
int minSpeed = 1;
int maxSpeed = 40;
Random random = new Random();
this.startSpeed = random.nextInt(maxSpeed - minSpeed + 1) + minSpeed;
}
protected int getSpeed(){
return startSpeed;
}
}
class Bicycle extends VehicleConstructor{
public void Bicycle(){
System.out.println(getSpeed());
}
}
public class Vehicle{
public static void main(String[] args){
Bicycle bicycle = new Bicycle();
}
}
I want to create object Bicycle which extends VehicleConstructor and call method getSpeed() from parent. The problem is that i get an error:
Error: Main method not found in class Bicycle, please define the main
method as: public static void main(String[] args)
As far as i know in Java constructors are with the same name as the class, so i have
public void Bicycle(){
System.out.println(getSpeed());
}
But error says that i need public static void main, and so the other classes also need to be with static, but i don't want this. Is it possible somehow create object without need of static method in it?
public void Bicycle(){ //This is a method
public Bicycle(){ //This is a constructor
Constructor's don't have any return type, not even void.
The error is self evident.. you dont have a main method, or for some reason, bicycle is defined as entry point when it should not be. After a second glance, looks like your Vehicle should be defined as the entry point, and its not.
p.s your class hierarchy is confusing.
create a separate class having main method to test (without this your program will not execute as it is the starting point) where you can create constructors of your classes
Your class works fine for me..What is the name of the file in which you have written code?File name should be equal to public class name..
I am guessing you are trying to run this class by itself. Java runtime needs that
public static void main(String[] args)
method when you try to run the class on its own. Try to create another Java class like Test.java that has main function and call the constructor inside it. Be sure to run Test.java otherwise you will keep getting the same error.
please , try to seperate the classes into seperates files, and name the files as the name of classes. then you add a public static void main(String[]arg) in the Bicycle class. then run it and you will see the results.
The problem is not at compile time, because even if you compile those files separately, they should compile fine. My guess is you are probably using an IDE (Netbeans or Eclipse) and you are not setting up Vehicle.java as the main class.

Multiple main() methods in java

I was wondering what the effect of creating extra main methods would do to your code.
For example,
public class TestClass {
public static void main (String[] args){
TestClass foo = new TestClass();
}
}
After the program initially starts up, foo will be created and it would have another public main method inside it. Will that cause any errors?
It will cause no errors. Just because you initialize an object, doesn't mean the main method gets executed. Java will only initially call the main method of the class passed to it, like
>java TestClass
However, doing something like:
public class TestClass
{
public static void main (String[] args)
{
TestClass foo = new TestClass();
foo.main(args);
}
}
Or
public class TestClass
{
public TestClass()
{
//This gets executed when you create an instance of TestClass
main(null);
}
public static void main (String[] args)
{
TestClass foo = new TestClass();
}
}
That would cause a StackOverflowError, because you are explicitly calling TestClass's main method, which will then call the main method again, and again, and again, and....
When in doubt, just test it out :-)
The main method is static, which means it belongs to the class rather than the object. So the object won't have another main method inside it at all.
You could call the main method on instances of the object, but if you do that it's literally just another way of calling TestClass.main() (and it's frowned upon by many, including me, to call a static method on an instance of an object anyway.)
If you're referring to multiple main methods in the same program, then this isn't a problem either. The main class is simply specified and its main method is executed to start the program (in the case of a jar file this is the main-class attribute in the manifest file.)
It won't have an additional main-method, as main is static. So it's once per class.
If you have multiple main-methods in your project, you will specify which one to launch when starting your application.
This is perfectly fine. Having multiple main methods doesn't cause any problems. When you first start a Java program, execution begins in some function called main in a class specified by the user or by the .jar file. Once the program has started running, all the other functions called main are essentially ignored or treated like other functions.
After searching for a Java Class with multiple main() methods or in plain words, overloaded main() methods, I came up with an example of my own. Please have a look
public class MultipleMain{
public static void main(String args[]){
main(1);
main('c');
main("MyString");
}
public static void main(int i){
System.out.println("Inside Overloaded main()");
}
public static void main(char i){
System.out.println("Inside Overloaded main()");
}
public static void main(String str){
System.out.println("Inside Overloaded main()");
}
}
I tested this Java Code on JDK 1.7 and works like a charm !
You need "public static void main(String args[])" to start with and then you can call overloaded main methods inside this main and it should work for sure.
Any comments and suggestion are highly appreciated. I am just a novice Java Developer willing to develop my Java skills.
Thanks,
PK
No, you can have any number of main-methods in a project. Since you specify which one you want to use when you launch the program it doesn't cause any conflicts.
You can have only one main method in one class, But you can call one main method to the another explicitly
class Expmain
{
public static void main(String[] ar)
{
System.out.println("main 1");
}
}
class Expmain1
{
public static void main(String[] ar)
{
System.out.println("main 2");
Expmain.main(ar);
}
}
when you run your Java class it will always look for the signature public static void main(String args[]) in the class. So suppose if you invoking by command line argument, it will look for the method Signature in the class and will not invoke other until if u explicitly inoke it by its class name.
class MainMethod1{
public static void main(String[] ags){
System.out.println("Hi main 1");
testig2 y = new testig2();
//in this case MainMethod1 is invoked/.......
// String[] a = new String[10];
// testig2.main(a);
}
}
class MainMethod2{
public static void main(String[] ags){
System.out.println("Hi main 2");
}
}
But when you try the same from eclipse it will ask for which class to compile. Means MainMethod1 or Mainmethod2. So if te class has the exact signature they can be used as individual entry point to start the application.
Coming to your question, If you remove the signature as u did above by changing the argument if main method. It will act as a normal method.
It is all about the execution engine of JVM. Remember, you write >java com.abc.MainClass on cmd prompt.
It explains everything. If main method is not found here it throws a run time Error:Main Method Not Found in class MainClass.
Now if main method is found here, it acts as the first point when Program Counters have to map and start executing the instructions. Referred classes are loaded then, referred methods may be called using the instances created inside. So, main is class specific though one class can have only one main method.
Please note, main method's signature never changes. You can have two overloaded main methods in same class, like
public static void main(String[] args) {}
public static void main() {} //overloaded in same class.
During Static binding, the original main is resolved and identified by execution engine.
Another interesting point to consider is a case where you have two different classes in of java file.
For example, you have Java file with two classes:
public class FirstClassMultiply {
public static void main (String args[]){
System.out.println("Using FirstClassMultiply");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiple is :" + mult.multiply(2, 4));
}
public static void main (int i){
System.out.println("Using FirstClassMultiply with integer argument");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiply is :" + mult.multiply(2, 5));
}
int multiply(int a, int b) {
return (a * b);
}
}
class SecondClass {
public static void main(String args[]) {
System.out.println("Using SecondClass");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiply is :" + mult.multiply(2, 3));
FirstClassMultiply.main(null);
FirstClassMultiply.main(1);
}
}
Compiling it with javac FirstClassMultiply.java will generate two .class files, first one is FirstClassMultiply.class and second one is SecondClass.class
And in order to run it you will need to do it for the generated .class files: java FirstClassMultiply and java SecondClass, not the original filename file.
Please note a couple of additional points:
You will be able to run SecondClass.class although it's class wasn't public in the original file!
FirstClassMultiply overloading of the main method
of is totally fine, but, the only entry point to your prog
will be the main method with String args[] argument.

Categories