Calling external class and methods - java

To start off I am in the beginning stages of learning Java and I am working on different exercises.
One of the exercises gives me this external class: http://pastebin.com/g8hCTRCc
I need to write an application to Calculate and print the maximum and the minimum of two rational numbers defined in the program as variables.
So far I have imported the class (I believe correctly) but I have no idea how to call methods from there.
package Rational;
import Rational.add;
public class test {
public static void add(String[] args){
}
}
Any help would be greatly appreciated.

Start by creating an instance of the class using its constructor. It appears most methods on the class only accept an instance of Rational as an argument, so a second instance of Rational must be created. Pass the second instance of Rational into the add() method of the first, which will return a new instance of Rational. All of this code should be included in a main method for execution. The import statement should also be modified to exclude add since imports require a fully qualified class name, not a method on a class.
package Rational;
import Rational;
public class Test {
public static void main(String[] args) {
Rational rational = new Rational(1,2);
Rational rational2 = new Rational(1,2);
Rational rationalTotal = rational.add(rational2);
}
}

Related

correct way to write class inside a subfolder in java? [duplicate]

This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
What is the purpose of defining a package in a Java file? [closed]
(11 answers)
Closed 6 months ago.
I am just starting to learn Java. I have made a project of Java using Visual Studio Code. The file path looks like this project/src/own/test.java.
I have written a simple program:
package own;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class test {
public static void main (String[] args){
int randomNumber = new Random().nextInt(7);
System.out.println("Enter a number");
Scanner keyboard = new Scanner(System.in);
int inputNumber = keyboard.nextInt();
if (randomNumber == inputNumber){
System.out.println("You won!");
}else{
System.out.println("You loose!");
}
keyboard.close();
}
}
Every time I run this is the vscode terminal, it says:
Error: Could not find or load main class test
But it runs fine if package own; line is not there. Vscode automatically included this line. Can anyone tell me why that is so? What is the use of package own.
Classes in Java almost always have to specify their "package...". Almost because there are some exceptions.
This reserved word is used for several important things, such as:
With package you identify in which zone of the project your class is located, in general, each java project has src/main/java/mypackage
src, main, and java are directories, not packages (you can look up the difference between these). So the classes here will not have a package, you can execute a main method but this class will be invisible inside your project
If you are at the "mypackage" level, from this path the class is already visible inside your project and the class will carry the "package mypackage";
By having your class with "package mypackage;" you can import this class to another class, and use the methods of the first class in the second class
package mypackage;
public class ClassOne {
public static String goodMorning(){
System.out.println("good morning");
}
}
And this class is in another file
package mypackage;
import mypackage.ClassOne;
public class ClassTwo{
public static void main(String args...){
ClassOne.goodMorning();
}
}
If you know PHP it works similar to "require_once" (although they are similar import and require_once do not work the same)
I mentioned above about "visibility" and it is that packages are also used to know the scope of an access modifier, in java there are 4 of these: public, private, protected and default (by default it is when you do not put an access modifier )
//public access modifier
public class One{
public String attribute;
public void method(){
}
}
//private access modifier
private class Two{
private String attribute;
private void method(){
}
}
//protected access modifier
protected class Three{
protected String attribute;
protected void method(){
}
}
//default access modifier
class Four{
String attribute;
void method(){
}
}
Find out what each one is for.
And another thing it is useful for, is organizing classes by packages, you can organize a collection of classes in a better way, this is important for large projects.
There are still more things but as you say that you are learning I do not want to overload you with information, go easy, greetings.

Constructor behaving like a method

I'm new to Java so not really sure if it's an error on my part. My project has two packages within. I'm trying to use an object belonging to a class of package lovo in an object of a class of package j2. The constructor of object belonging to package lovo is now being treated as a method. Why is that?
package j2;
import lovo.kulo;
public class J2
{
public static void main(String[] args)
{
kulo kla ;
kla = new kulo();
//kla.kulo();
}
}
package lovo;
public class kulo {
public void kulo(){
System.out.print("This is supposed to be a constructor");}
}
When i run there is no output, however when i remove the comment and add it as code there is an output. Since it's a constructor shouldn't it print as soon as the object is created?
It is indeed a method. To make it a constructor, remove the void return type. It'll also be less confusing if you follow Java naming conventions and begin class names (and therefore constructor names) with an uppercase letter.

Why am I being forced to change methods and varibles to static when calling them from my main method? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Cannot make a static reference to the non-static method
(8 answers)
Closed 5 years ago.
For some reason when I'm trying to call methods using a main method or try changing variables declared outside the main method I get forced into having to change everything to static. This is fine in places but when it comes to needing to change values later in the code for example using a Scanner for input the main method just takes it to a whole new level trying to make me change the Scanner library etc.
This example shows what happens if I try calling a method.
This example shows what happens when I try alter the value of a variable declared outside my main method.
I have never faced an issue like this before when writing java code I've tried recreating the classes/ project files etc but nothing works. I've tried looking everywhere for a solution but I can't seem to find one probably due to the fact that I don't know what to search for. I've probably made myself look like a right idiot with my title haha! Any suggestions people?? Thanks in advance!
Maisy
It can be a bit confusing to get out of "static land" once you are in your main() method. One easy way is to have another object contain your "real" (non-static) top level code and then your main method creates that object and starts it off.
public static void main() {
MyEngine engine = new MyEngine();
// core logic inside of start()
engine.start();
}
I hope that this was clear enough for you. Good luck Maisy!
When calling methods form a main you have to instantiate the class they are in, unless it's a static function
this is because that a class is a sort of template and there is nothing saved about it before it get instantiated
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
}
public method method(){}
}
in the example above i instantiated a TestClass and then called on the testClass instance
there is some functions and variables on classes you might want static, because a static on a class is shared between ALL instances, and can be called on the class, say you want to know how many instances were created then something like this can be done.
public class TestClass{
public static void main(String[] args){
TestClass testClass = new TestClass();
testClass.method();
System.out.print(TestClass.instances +""); // note that i call on
//the class and not on an instance for this static variable, and that the + ""
//is to cast the int to a string
}
public static int instances = 0; // static shared variable
public TestClass(){instances++;} // constructor
public method method(){}
}
You need to do some Object Oriented Programming tutorial and to learn some basic.
As answer for your problem to call without using static you have to create an instance of the main Class
let suppose the following class Foo
public class Foo{
private int myVarInteger;
public int getMyVarInteger(){ return this.myVarInteger;}
public void setMyVarInteger(int value){this.myVarInteger = value;}
public static void main(String[] args){
Foo myClassInstanceObject = new Foo();
// now we can access the methods
myClassInstanceObject.setMyVarInteger(5);
System.out.println("value ="+myClassInstance.getMyVarInteger());
}
}

Using a instance of a method

I was wondering if someone could help explain how to call a instance of a class.
For example originally I had a file called "Driver"
Then it has a main method that has all the instances needed for a file to run.
Then in that main file it access another file called with a "Games".
So when I run the program "Driver" which has the following code:
import java.util.*;
public class Driver
{
public static void main (String[] args)
{
GameRunner roul = new GameRunner ();
}
}
Then to call an instance of that other file I have something like. Also to make the code work I should have the main method like:
import java.util.*;
public class Driver
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
int number = 3;
int userChoice = 0;
GameRunner roul = new GameRunner ();
}
}
Then my other file has something like:
import java.util.*;
class GameRunner
{
public static void roul(Scanner in, int number, int userChoice)
{
Guessing this is still wrong because the driver class should only have :
GameRunner roul = new GameRunner ();
I know it's kinda hard to explain what I'm asking. I hope someone understands.
Thanks.
I strongly recommend reading this (official) tutorial from the people who made Java: https://docs.oracle.com/javase/tutorial/java/concepts/index.html
(No, seriously. Read that tutorial. I linked to the section specifically on object-oriented programming, which explains what you are asking about. It's very useful).
Now to answer your question more directly.
Your roul method is a "class method" (rather than an "instance method") because it has the keyword static in front of its definition. This means that you invoke it using the name of the class, rather than by using a specific object (instance) that you created.
So in order to call the roul method of GameRunner, do the following in your main:
GameRunner.roul(in, number, userChoice);
It is not necessary to instantiate GameRunner unless it has a non-static method that you need to invoke. So unless that's the case, don't do the following:
GameRunner roul = new GameRunner ();
Finally, note that the names of your arguments do not have to be the same as the names of your parameters, as long as their types are the same. The "parameters" are the variables you used when you defined the method. The "arguments" the actual variables you pass to the method.
For example, a method definition has parameters:
public static void myMethod(int parameter1, int parameter2) {
/* do stuff */
}
Whereas a method invocation has arguments that can have a different name:
MyClass.myMethod(number1, number2);
public class Driver {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int number = 3;
int userChoice = 0;
GameRunner runner = new GameRunner ();
// The following line will invoke the target method of your game runner instance.
runner.roul(in, number, userChoice);
}
}
Declare the class and method static then call like this:
GameRunner.roul(); // pass in arguments if needed
public static void run() is the entry point into your application you don't need another one. it looks like you need to brush up on Object Oriented basics.
if you're trying to make a game perhaps you could start with a tutorial? i would suggest using a game library like Lightweight Java Game Library. go ahead and google for some tutorials.

How to give a programmatic support to a class with a main

I'm sorry for the title but I can't really find another way to express it. I need to create a class with a double function, if you give to it a file as input from the console or terminal it gives back a print of it's calculations, but the class can be also used as subroutine and give a file to another class for further calculation.
To implement the first task I must define a main to accept input from console like this
java MyClass myfile.file
But then I can not simply get an instance the class inside something else like this
MyClass myClass = new MyClass(file);
cause I will always get an error from the main(IndexOutOfBound since args it's just an empty array).
How can I fix this? I must use the same class to do so, I can not build another class for the subroutine function.
Something like:
public class MyClass {
public MyClass(String nameOfFile) {
...
}
public void doSomething() {
}
public static void main(String[] args) {
MyClass myClass = new MyClass(args[0]);
myClass.doSomething();
}
}
So your main method simply interprets the incoming arguments (as file names or similar), then instantiates and executes your class as another library might.

Categories

Resources