Calling method from another class unsuccessful - java

I have a main class called Main.java and the other class called Movements.java
I tried calling upon a method from the Movements.java into the Main.java but it was not what I expected.
Main.java:
package game;
public class Main {
Movements shift = new Movements();
public void main String(String[] args) {
while (true){
//body here//
}
}
public static void startProgram {
//body here//
}
public static int variableName {
//body here//
}
public static boolean isInputValid {
//body here//
}
public Chess(){
shift.analyzeInput();
shift.makeTurn();
}
}
Movements.java:
package game;
public class Movements {
public static void analyzeInput(String info){
StringTokenizer token = null;
EasyWriter show = new EasyWriter();
int tally = 0;
info = info.toLowerCase();
info = info.trim();
String[] array = new String[100];
token = new StringTokenizer(info);
while (token.hasMoreTokens()) {
array[tally] = token.nextToken();
tally++;
}
if (tally > 0 && tally < 4){
if (tally == 1){
if (array[0].equals("resign")){
if (Main.timeForWhitePlayer){
show.println("Black wins");
System.exit(1);
}else{
show.println("White wins");
System.exit(1);
}
}else if (array[0].equals("draw")){
if (Main.drawRequest == true){
show.println("It's a draw");
System.exit(1);
}else{
show.println("You must ask the opponent if they are willing to call the game a draw first.");
}
}else{
show.println("Invalid input. Please try again. ");
}
}else if (tally == 2) {
Main.presentPosition = array[0];
Main.nextPosition = array[1];
if (Main.presentPosition.length() == 2 && Main.nextPosition.length() == 2 ){
makeTurn();
}else{
show.println("Invalid input. Please try again.");
}
}
Main.presentPosition = null;
Main.nextPosition = null;
Main.thirdArgument = null;
}
public static void makeTurn() {
//body in here//
}
}
I'm using Eclipse IDE and it states that Syntax error on token "makeTurn", Identifier expected after this token. Have I done something wrong?

You don't need to create an instance since the method is static. You can simply call Movements.makeTurn(). And also I guess you meant to change Movements mv = new Move(); to Movements mv = new Movements(); if you do not have a Move class. If you do, then it must extend the type Movements

My guess, you're calling shift.makeTurn(); outside of any method or constructor, naked in the class. If so, you can't do that as you must make method calls that don't initialize a variable within a method or constructor or some similar block (static initializer block for instance).
For instance, to simplify, assuming you have a Movements class like so:
public class Movements {
// looks like this should not be static
public void makeTurn() {
}
}
and a Main class like so:
public class Main {
Movements shift = new Movements();
shift.makeTurn(); // you can't call this here!
public Main() {
shift.makeTurn(); // but you can do it here!
}
public static void main(String[] args) {
Movements shift = new Movements();
shift.makeTurn(); // or you can do it here!
}
}
Edit: my assumption was correct -- you're making method calls outside of any method or constructor and the solution is simple: don't do that. Put those calls in whatever method or constructor they belong.
Other issues:
Your code has static overload -- overuse of the static modifier, making it a non-OOP program.
You're making way too many direct references of one class's fields in another, and this leads to code with lots of connections (called highly coupled code). This can lead to very hard to debug errors.

Don't name your class Main. It's confusing. main is what we call the method we use as the program entry point.
shift.makeTurn() is not within any method, constructor, or initialiser so you need to move it. You also need to decide if makeTurn() needs access to any properties that will be different in different instances of Movements (you called one shift). If so you can't make it static.
If you want to call using
shift.makeTurn();
then turn this:
public static void makeTurn() {
into this:
public void makeTurn() {
Otherwise do what #TameHog told you to do.
A static method isn't bound to an instance like shift. It's bound to a class like Movements. It's all about what makeTurn() needs access to. Though non static is considered more flexable. If you understand that you should be able to decide which to do on your own.

You cannot call methods within the class definition. Instead you must call the method within a method or initializer.
Using a method
package game;
public class Main {
public void main String(String[] args) {
shift.makeTurn();
while (true){
//body here//
}
}
public static void startProgram {
//body here//
}
public static int variableName {
//body here//
}
public static boolean isInputValid {
//body here//
}
Movements shift = new Movements();
}
Or, with the instantiation in the function,
package game;
public class Main {
public void main String(String[] args) {
Movements shift = new Movements();
shift.makeTurn();
while (true){
//body here//
}
}
public static void startProgram {
//body here//
}
public static int variableName {
//body here//
}
public static boolean isInputValid {
//body here//
}
}
Or with an initialiser
package game;
public class Main {
public void main String(String[] args) {
while (true){
//body here//
}
}
public static void startProgram {
//body here//
}
public static int variableName {
//body here//
}
public static boolean isInputValid {
//body here//
}
Movements shift = new Movements();
{ shift.makeTurn();}
}

Related

How do I call a method that has a variable passed through it?

I'm trying to call a method from within another method. I'm understanding this simply enough, until one of those methods needs a variable carried through, and then nothing I try works.
I know that I could do this in one method, but my coursework needs me to lay it out in such a way. Why doesn't this work?
public class test2 {
public static void testMethod() {
int randomNumber = 1;
}
public static void anotherTestMethod(int randomNumber) {
System.out.println(randomNumber);
}
public static void main(String[] args) {
anotherTestMethod();
}
}
You are calling a method that has an int parameter in its signature. You should pass that parameter when calling the method. I think you are trying to use a global variable, in that case, you should declare it outside any method, as a part of the class.
public class test2 {
public static int testMethod() {
int randomNumber = 1;
return randomNumber;
}
public static void anotherTestMethod() {
System.out.println(testMethod());
}
public static void main(String[] args) {
anotherTestMethod();
}
}

Pass a class method to another class method

Say I have the following class
class Application {
public Application() {...}
public void doSomething(final String logs) {
final String[] lines = logs.split("\\n");
for (final String line: lines) {
// Pass the line to every single checkForProp# item and do something with the response
}
}
private Optional<Action> checkForProp1(final String line) {
// Check if line has certain thing
// If so return an Action
}
// More of these "checks" here
}
Let's say every single response, would be added to a queue, and then returned something is done on that queue.
So instead of I calling each method manually, I want to have maybe an array of checker methods, and automatically loop through them, pass in the line, and add the response to a queue.
Can this be achieved?
You can implement your Action as interface:
public interface Action{
public void fireAction();
}
Those classes which implement Action will then override the method defined in the interface, such as checking a String.
Add the instances of Action to the list and you loop them accordingly.
Example:
for(Action a : actions)
a.fireAction();
If i understood your question correctly then following code may be help you.
import java.lang.reflect.Method;
public class AClass {
private void aMethod(){
System.out.println(" in a");
}
private void bMethod(){
System.out.println(" in b");
}
private void cMethod(){
System.out.println(" in c");
}
private void dMethod(){
System.out.println(" in d");
}
//50 more methods.
//method call the rest
public void callAll() {
Method[] methods = this.getClass().getDeclaredMethods();
try{
for (Method m : methods) {
if (m.getName().endsWith("Method")) {
//do stuff..
m.invoke(this,null);
}
}
}catch(Exception e){
}
}
public static void main(String[] args) {
AClass a=new AClass();
a.callAll();
}
}
Here Java Reflection is used.

Simple Pass Fail Java program

I am trying to write a Java function based off of the following question:
Write a program called CheckPassFail which prints "PASS" if the int variable "mark" is more than or equal to 50; or prints "FAIL" otherwise. The program shall always print “DONE” before exiting.
This is what I have so far:
import java.util.*;
import java.lang.*;
import java.io.*;
class CheckPassFail(){
int m;
public void GetGrade(int mark){
m = mark;
}
public void GradeCheck(int mark){
if(mark >= 50){
system.out.println("Pass");
}
else{
system.out.println("Fail");
}
public static void main(String[] args){
CheckPassFail grade = new GetGrade(66);
grade.GradeCheck(66);
}
}
I believe my issue has to do with the GetGrade class? I feel as if setting m = mark is unnecessary for this program. Please let me know if you see any other errors. Thank you.
Critical problems (these are preventing your program from compiling):
Your code is missing the closing brace } in the GradeCheck method.
There must not be parenthesis in class declarations, as in class CheckPassFail {
Java is case-sensitive. You must use System, not system, as in System.out.println();
Technical explanation: System refers to the builtin class java.lang.System. All java.lang classes are automatically available without you needing to import them.
GradeCheck is a method, not a class. You cannot create a new instance of it, or use the new operator with it, as you did with new GetGrade(66);
Non-critical (but nevertheless important) problems:
You seem to think that GetGrade is a constructor. It is not. That is not how constructors work. That is not how classes work. That is not how Java works.
The variable m is declared and assigned to, but never used.
Your program does not print "DONE" after executing, which was a requirement.
All of your imports are unused. You should not import extraneous packages.
The class CheckPassFail should be public. Most Java classes should be public.
Your indentation is inconsistent and makes your code less readable.
Cleaned-up version of your code:
public class CheckPassFail {
public int mark;
public CheckPassFail(int mark) {
this.mark = mark;
}
public void checkGrade() {
if(mark >= 50) {
System.out.println("PASS");
} else {
System.out.println("FAIL");
}
}
public static void main(String[] args) {
CheckPassFail checker = new CheckPassFail(66);
checker.checkGrade();
System.out.println("DONE");
}
}
GetGrade is not a class, it's a function. Therefore, it should be called without the 'new' keyword.
Class declaration syntax is wrong, there shouldn't be any parenthesis.
Considering what GradeCheck function is doing, GetGrade function is useless (unless you need it somewhere else).
'system' should be 'System' (in-built class from java.lang package).
Class names should start with upper-case letters and function names should start with lower-case letters (standard).
class CheckPassFail {
public void gradeCheck(int mark) {
if(mark >= 50) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
}
}
public static void main(String[] args) {
CheckPassFail check = new CheckPassFail();
check.gradeCheck(66);
}
}
class CheckPassFail
{
int m;
CheckPassFail(int mark){
m = mark;
}
public void gradeCheck(int mark){
if(mark >= 50){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}}
public static void main(String[] args) {
CheckPassFail grade = new CheckPassFail(66);
grade.gradeCheck(66);
}}
class CheckPassFail {
public void gradeCheck(int mark) {
if(mark >= 50) {
System.out.println("Pass");
}
else {
System.out.println("Fail");
}
}
public static void main(String[] args) {
CheckPassFail grade = new CheckPassFail();
grade.gradeCheck(66);
}
}

Iterate through inherited classes and call their static methods

I want to iterate through some classes, that inherit from the same superclass.
They all have the same static method, but how can I call it?
I tried it like this, but that does not work:
public abstract class Tower {
private static int text = 5;
public static int getText() {
return text;
}
}
public class aTower extends Tower {
private static int text = 10;
public static int getText() {
return text;
}
}
public class Main {
public static void main(String [] args) {
LinkedList<Class<?extends Tower>> towers = new LinkedList<>();
towers.add(aTower.class);
for (int i = 0; i < towers.size(); i++) {
towers.get(i).getText(); //Does not work
}
}
}
Context
I want to have a list of classes that inherit from Tower for calling static methods of them, for getting e.g. their texture. Is there any other way to do that?
Edit: The main goal is, that I will have many different Towerclasses in a list, and there should be a menu with every towerclass. To paint the menu, I want to get for example the texture, the name, etc. When you click on the menu entry, then you should get an object of the specific tower and you can build it somewhere. But I do not like the idea of having a list of more or less unused instances, and therefore I thought having a static method is the right solution.
Check out Java Interfaces though as already stated they wouldn't be static methods.
public interface ITower {
public String getText();
}
from this point you define your tower objects that implement ITower and then inside main:
public class Main {
public static void main(String [] args) {
List<ITower> towers = new LinkedList<>();
// create your tower objects and add them to the list
towers.add(new ATower());
towers.add(new BTower());
for (ITower iObj : towers) {
iObj.getText();
}
}
}
By converting your static method to an instance method, and using a static field within each subclass, you can get this to work:
public abstract class Tower {
private static int text = 5;
public int getText() {
return text;
}
}
and
public class aTower extends Tower {
private static int text = 10;
#Override public int getText() {
return text;
}
}
and
public class Main {
public static void main(String [] args) {
LinkedList<aTower> towers = new LinkedList<>();
towers.add(new aTower());
for (int i = 0; i < towers.size(); i++) {
towers.get(i).getText();
}
}
}
In your original main() method, you created a List instance for Class objects. I think you had really intended for this to contain aTower instances. This is important because class Class will not have a getText() method.
Polymorphism doesn't work with static methods. Why do you want getText() to be static?
If you have a no-arg constructor in Tower you can use reflection to create an instance from a class name.
Class<Tower> towerClass = (Class<Tower>) Class.forName(classString);
Tower tower = towerClass.newInstance();
tower.staticMethod();

Java initial values?

If I were to do something such as:
public class Game
{
private boolean RUNNING = true;
Game()
{
}
public static void main(String[] args)
{
Game game = new Game();
}
}
At what point in time would RUNNING = true?
edit: for clarity, at what point in the program would running be set to true. ex: Before the constructor, after the constructor, etc.
It will be set to true before the constructor. You can use it in the constructor as true.
This code explains itself:
public class SuperClass
{
String superField = getString("superField");
public SuperClass()
{
System.out.println("SuperClass()");
}
public static String getString(String fieldName)
{
System.out.println(fieldName + " is set");
return "";
}
public static void main(String[] args)
{
new ChildClass();
}
}
class ChildClass extends SuperClass
{
String childField = getString("childField");
public ChildClass()
{
System.out.println("ChildClass()");
}
}
OUTPUT:
superField is set
SuperClass()
childField is set
ChildClass()
When the constructor is called using the new operator all non-static members of the class are initialized before the code inside the constructor is executed. You can use the debugger and step into that call and see where it goes first. Static members are initialized when the class is loaded and for the first time accessed (see this question for more detailed info about static members).
private boolean RUNNING = true;
Game() {
}
is exactly the same as
private boolean RUNNING;
Game() {
RUNNING = true;
}
Actually, the comiler will move the initialization at the beginning of the constructor. The value will then be set when instantiating an object of that class.
When you try to use local variables which not manually initialized, you will get a compile time error.
public static void main(String args[]){
int a;
System.out.pritnln(a); //error
}
But it's not the case with instance variables. This itself shows that they are ready for usage before the constructor even.
public class Example{
private int a;
public Example(){
System.out.println(a); //No error
}
public int getA(){
return a; //No error
}
}
I hope this intuition answers your question..........

Categories

Resources