invoking method in main method in Java - java

I have a question regarding to using method in main class, here is my code for a Race class:
import java.util.ArrayList;
public class Race {
private ArrayList<Car>cars;
public Race(){
cars = new ArrayList<Car>();
}
public void addCars(Car car){
cars.add(car);
}
}
The above is what I have done to make an arraylist for the cars that I am ready to put in by using a main method in another class:
public class Test {
public static void main(String[] args) {
Car toyota = new Car("Toyota",1.0,1.0,2.0,2.0);
cars.addCars(toyota);
}
}
However, it has error in the last line, it shows "cars cannot be resolved",I am not sure how should I fix it, maybe writing a getter method in the Race class?

Create an instance of race and call addCars
Race race = new Race();
race.addCars(toyota);

cars does not exist in that context, you might want to stick to the convention on having lowercase variable names, as well.
Change your Test class to something similar to this:
public class Test {
public static void main(String[] args) {
Race race = new Race();
Car toyota=new Car("Toyota",1.0,1.0,2.0,2.0);
race.addCars(toyota);
}
}
You want to add cars to the race, not cars (which does not exist).
To add cars to a race, you first need to make one.
By adding cars to the race, it will internally add it to the cars list. (Because you made it so)
You problem is basically that you are trying to use a variable that is outside the scope. (Somewhere else, basically)
Since I don't know your exact problem, I can't really help you further, but you might want to save the race in a field rather than a local variable, it all depends on what you want to do.

Related

Understanding Command Pattern and why do we need an interface?

I am trying to reduce the if else constructs which I use to display appropriate information in a ListView (Android)
I have created a simple Command Interface for learning purpose and here it is:
interface CommandPattern {
void execute();
}
public class CommandA implements CommandPattern {
public void execute(){
System.out.println("I am Command A");
}
}
public class CommandB implements CommandPattern{
public void execute(){
System.out.println("I am Command B");
}
}
Then my Main is as follows:
public class MainClass {
static Map<String,CommandPattern> myCommand; //= new Map<String, CommandPattern>();
public static void main(String[] args){
myCommand = new HashMap<String, CommandPattern>();
myCommand.put("A",new CommandA());
myCommand.put("B",new CommandB());
// In an ideal condition I will invoke the below by supplying values I get from the Database
// myCommand.get(valuefromDB).execute();
myCommand.get("B").execute();
myCommand.get("A").execute();
}
}
What I have done above can be achieved without using the interface and extending from one by simply calling the execute method of an appropriate class. What is the reason of using an interface?
Secondly does it mean that for each if - else branch I have to construct a new class? Cant this be done using an enum?
The background of the problem:
I have a database and I fetch values based on this data anda number of flags I process data to be displayed in each row. This if else construct has gone beyond what I can ever maintain. So I want to introduce a Command pattern.
Implementing an interface: ClassA has some behavior (i.e., one or more methods), defined by an InterfaceB, that it supports.
Extending a class says that ClassA is a 'special case' of the ClassB being extended; i.e., that ClassA has all of the characteristics (data and methods) of ClassB plus additions and/or changes.
You can implement the Command pattern with either one; which one is appropriate depends on the specific situation. What is to be avoided is using inheritance where the 'special case' does not apply; put another way, do not use inheritance just to have a common method among classes.
EDIT: as to "Can't this be done using an Enum?", it isn't clear what you mean by 'this'.
To demonstrate the power of using an interface:
public class MainClass {
static List<CommandPattern> myCommand;
public static void main(String[] args){
myCommand = new ArrayList<>();
myCommand.add(new CommandA());
myCommand.add(new CommandB());
for (CommandPattern command: myCommand) {
command.execute();
}
}
}
This example shows that two different commands can be executed using the interface. The for-loop is only aware of the fact that it can call èxecute() on the object, but the actual code being executed varies depending on the concrete object adhering to the interface.
Since it is if-else branching you wish to get rid of, I think you might want to look into the Strategy Pattern as well.

Can I use variables declared and assigned inside the main in other class?

I tried to access a variable in the main class from another class. I don't know if it's possible but I need those variables. If there is a way please show me. This is the simple example.
public class A(){
public static String status;
public static void main(String [] args){
Scanner s = new Scanner(System.in);
System.out.println("Deadlock or no deadlock (y/n)");
status = s.nextline();
......
}
Then I want to use this variable "status" in another class which implements a runnable (thread). If status is "y" then a particular block of codes (if/else) inside the run methon will executes.
Anyone point me how do I call the main class so I can access the variable status from my the runner class. Thanks.
The field status in class A is public and static, so you can call it from wherever you like.
public class B {
public void myMethod() {
System.out.println("A's status is " + A.status);
}
}
A point on terminology: A here is a class, which represents an object. main happens to be a method within that class A. So you'd say that status belongs to A, not to main.
No java is pass by value not pass by reference. You could follow the example I'm linking and see if that helps though.link You could make it static and it would be usable that way but any operations on it would change when ever you perform any on it hence static.

How to access an object from a different class and package?

So, I am a learning programmer and I started to learn Java 2 months ago as a course at my university. I really like to program in my spare time and I'm currently trying to make a game. There is one problem at the moment which I just can't solve.
I have a class called Move, and I declare in my class called Start:
Move move1 = new Move();
Now when I'm back in my Move class, I would like to access this move1 but it doesn't let me. It says:classname cannot be resolved.
To clarify:
public class Move {
private String s = null;
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}
public void setList() {
System.out.println(move1.getName() + move2.getName()); // This won't work
}
}
And the start class:
public class Start {
public static void main(String[] args) {
Move move1 = new Move();
Move move2 = new Move();
move1.setName(kick);
move2.setName(punch);
}
}
It would be awesome if someone could help me out!
-edit
OK! I got a few reactions but I didn't really get the answer I need. I know now i can use this instead of the object name but what if I want to use a second object? I changed code the above.
The problem you have is that the names move1 and move2 are out of scope in the setList method. They're defined in Start.main as local variables, so they are only visible there.
There are a innumerable ways you can solve this. The most straight-forward way is to move the setList method to Start. Because you're calling it from main, which is a static method, setList will also have to be static.
public class Start {
public static void main(String[] args) {
Move move1 = new Move();
Move move2 = new Move();
move1.setName(kick);
move2.setName(punch);
setList(move1, move2);
}
public static void setList(Move move1, Move move2) {
System.out.println(move1.getName() + move2.getName());
}
}
If you think setList should be in the Move class, you'll need to pass the second move as a parameter.
public class Move {
...
public void setList(Move other) {
System.out.println(this.getName() + other.getName());
}
}
You don't need to say move1.getName(). You can say this.getName() instead. The keyword this refers to whatever object is calling the method - in this case, move1.
This is because the object move1 only exists in the scope of the main method in Start. Therefore, "move1" is meaningless anywhere other than main.
In reality, the keyword this can be omitted; you could just say getName() without putting anything in front of it.
move1 is the object of Move class define in the Start class so you cant access it.You can simply access the method of Move class with below line.
System.out.println(getName()); // THis will work
The correct way to access current move object (move1) is using this key word. You could say System.out.println(this.getName()); in Move class.
Maybe you didn't add import of class Move? It necessary when you access an object from a different package.

Need help to get two classes to assist each other

i'm currently just fooling around with different classes to test how they work together, but im getting an error message in NetBeans that i cant solve. Here's my code:
class first_class.java
public class first_class {
private second_class state;
int test_tal=2;
public void test (int n) {
if (n>2) {
System.out.println("HELLO");
}
else {
System.out.println("GOODBYE");
}
}
public static void main(String[] args) {
state.john();
TestingFunStuff.test(2);
}
}
class second_class
public class second_class {
first_class state;
public int john () {
if (state.test_tal==2) {
return 4;
}
else {
return 5;
}
}
}
Apparently i can't run the method "john" in my main class, because "non static variable state cannot be referenced from a static context" and the method "test" because "non static method test(int) cannot be referenced from a static context".
What does this mean exactly?
Screenshot of the error shown in netbeans: http://imageshack.us/photo/my-images/26/funstufffirstclassnetbe.png/
It means state must be declared as a static member if you're going to use it from a static method, or you need an instance of first_class from which you can access a non-static member. In the latter case, you'll need to provide a getter method (or make it public, but ew).
Also, you don't instantiate an instance of second_class, so after it compiles, you'll get a NullPointerException: static or not, there needs to be an instance to access an instance method.
I might recommend following Java naming conventions, use camelCase instead of under_scores, and start class names with upper-case letters.
The trick here to get rid of the error message is to move the heavy work outside of main. Let's assume that both lines are part of a setup routine.
state.john();
TestingFunStuff.test(2);
We could create a function called setup which contains the two lines.
public void setup() {
state.john();
TestingFunStuff.test(2);
}
Now the main routine can call setup instead, and the error is gone.
public static void main(String[] args) {
setup();
}
However, the other members are correct in that your instantiation needs some cleanup as well. If you are new to objects and getting them to work together might I recommend the Head First Java book. Good first read (note first not reference) and not all that expensive.
Classes can have two types of members by initialization: static and dynamic (default). This controls the time the member is allocated.
Static is allocated at class declaration time, so is always available, cannot be inherited/overridden, etc. Dynamic is allocated at class instantiation time, so you have to new your class if you want to access such members...
It is like BSS vs heap (malloc'd) memory in C, if that helps..

set interface problem and objects

sorry for bad Subject of topic but i couldnt find out what to write proper. (please correct topic if it gives missunderstood).
So my problem is:
I have interface Shape and two classes implements after this Circle and Square.
I need to write class which will collect Circle and Square. It must be one of methods of collecting which will not add any duplicate objects. I've chosen "set" after reading in documentation of java. But i am not sure if it was good idea. (i can use one of the four methods: map. set. list. or queque).
After all I created another class named ShapeSet and method
public void ShapeSet(Shape Set)
It looks like this:
public class ShapeSet {
public ShapeSet() {}
Set <Shape> setting; //is it wrong?
public void addShape(Shape shape) {
setting.add(shape);
}
...
}
After that thinking that i am doing right i created in main class, constructor defining square and circle. I created also ShapeSet ss.
public static void main(String[] args) {
// TODO code application logic here
ShapeSet ss = new shapes.ShapeSet();
Shape c = new Circle(3);
Shape s = new Square(4);
ss.addShape(c);
ss.addShape(s);
ss.iterator();
}
But while running program i got error on line ss.addShape(x), netbeans complains that he found null exception. Why? ;( I think types inputed to method shapeset was wrong and maybe bad position of declaring set setting. But how to fix that? I am total novice in java. I appreciate for a help. Thanks in advance.
The answer about the NullPointerException is probably because in your ShapeSet class, you haven't allocated the member field 'setting' as in
Set <Shape> setting = new HashSet<Shape>();
The question I have however, is why have a ShapeSet class at all? It seems you only need to have Set as a field in the class that has the main method.
You forgot to initialize your field setting
public class ShapeSet {
public ShapeSet() {}
Set <Shape> setting = new HashSet<Shape>();
public void addShape(Shape shape) {
setting.add(shape);
}
...
}
I agree with #MeBigFatGuy - you don't need your ShapeSet class. You can code your main like this:
public static void main(String[] args) {
Set<Shape> ss = new HashSet<Shape>(); // or some other Set concrete class
Shape c = new Circle(3);
Shape s = new Square(4);
ss.add(c);
ss.add(s);
ss.iterator(); // actually, you'd want to do something with the iterator
}

Categories

Resources