Calling a method in java - java

public class DialogBox {
public static void main (String arg[]) {
String inputCourseCode;
inputCourseCode = this.inputCourseCode();
}
public String inputCourseCode() {
String input = JOptionPane.showInputDialog("Input the course code of this course:");
return input;
}
}
How to call the method inputCourseCode in main function?

You need to have an instance of DialogBox in order to call the inputCourseCode method.
For example:
public static void main (String arg[])
{
String inputCourseCode;
DialogBox box = new DialogBox();
inputCourseCode = box.inputCourseCode();
}
main is a static method; consequently, it does not have access to a 'this' reference.

It's an instance method, so you need an instance of DialogBox to call the method.
public static void main (String arg[]) {
DialogBox foo = new DialogBox();
String inputCourseCode = foo.inputCourseCode();
}

It needs to be static
public static String inputCourseCode()
then within Main you remove the this.

public static void main (String arg[]) {
String inputCourseCode;
DialogBox d = new DialogBox(); //create instance
d.inputCourseCode(); //call method
}
inputCourseCode is a method of DialogBox class, you need a reference to an instance of that class to call it.
If you need to call that function without an istance class you need to declare it as static:
public static String inputCourseCode() {
String input = JOptionPane.showInputDialog("Input the course code of this course:");
return input;
}
Then you can call it from main without create an object:
public static void main (String arg[]) {
String inputCourseCode;
DialogBox.inputCourseCode(); //call static method
}

new DialogBox().inputCourseCode();
You need to instantiate your class to access non-static members.
See Java Tutorial: Understanding Instance and Class Members

Well it depends on your need.
If you want it to be tied at class level, then just make it static and remove 'this' from this.inputCourseCode() in the current code and it will work.
If you want it to be part of each object then you need to create object of DialogBox and call it explicitly as follows :
DialogBox dialogBox = new DialogBox();
dialogBox.inputCourseCode();

Related

How can I use non static variable(object ref) in static method without creating object inside that static method in java?is there any way to do it?

I'm new to Java. I get this error when running the code below
Cannot make a static reference to the non-static field universityObj
But not getting error while using
University universityObj = new University();
The code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
University universityObj;
public static void main(String[] args)
{
University universityObj = new University();
universityObj.name="Robert";
universityObj.stuno=12;
System.out.println(universityObj.name);
System.out.println(University.university_name);
display();
}
public void nonStaticDisplay()
{
System.out.println(name);
System.out.println(stuno);
}
public static void display()
{
universityObj = new University();
System.out.println(universityObj.name);
}
}
Let's go step by step.
The display() method should be non-static because it belongs to and should be used on the specific instance of the University class. Static methods can be used without creating an instance of some class. But in the case of the display() method, it wouldn't makes sense to do that because you need to display the university name, which firstly should be created and assigned.
It's not a good idea to create the object instance University universityObj inside the class in your case. Better to leave it only in the main method.
The university_name name is not static, so you can't access it without the class instance (object) like you're doing right now. University.university_name should be changed to universityObj.university_name.
These steps will bring us to a such piece of code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
public static void main(String[] args) {
University universityObj = new University();
universityObj.name = "Robert";
universityObj.stuno = 12;
System.out.println(universityObj.name);
System.out.println(universityObj.university_name);
universityObj.display();
}
public void display() {
System.out.println(name);
System.out.println(stuno);
}
}
Other things, which you should consider:
Read about encapsulation.
Use code formatting in your IDE. Example for IntelliJ IDEA.
Check the toString() method from the Object class. It's intended exactly for what you're trying to achieve with your display() method.
You might simply pass a reference to the instance you want to be displayed. Like,
public static void display(University universityObj)
{
System.out.println(universityObj.name);
}

I need to use an object created in one static method in another static method but have issue calling it

(This is a repost of a previous question I have where I modified the code so it is much easier to understand.)
public class LaptopSaleApp{
public static void main(String[] args){
selectLaptop();
selectSupportOptions(laptopOrder);//This parameter cannot be resolved into a variable
}
public static void selectLaptop(){
LaptopSalesOrder laptopOrder = new LaptopSalesOrder("Dell Latitude", 1399.00);
}
public static void selectSupportOptions(LaptopSalesOrder laptopOrder){
laptopOrder.setBasicIndicator(true);
}
}
I need two static methods here. The object has to be declared in the first method, and then is used in the second method for the setBasicIndicator setter. I then need to call both methods in my main to run the program, but I don't know what to put in the parameters for the method in the main.
You can't quite do this if the object is declared in the first method.
Here's what you should do:
public static void main(String[] args){
LaptopSalesOrder laptopOrder = selectLaptop();
selectSupportOptions(laptopOrder);
}
public static LaptopSalesOrder selectLaptop(){
return new LaptopSalesOrder("Dell Latitude", 1399.00);
}
public static void selectSupportOptions(LaptopSalesOrder laptopOrder){
laptopOrder.setBasicIndicator(true);
}

pass string to main method in another class

I'm creating a project that need to pass string from first program to second program but i need to pass string in main method of first class. I've googled but i cannot find what i need, mostly people use setter and getter to pass string between class but i cannot do that in main method.
How to pass string in main method of another class?
what i need is shown here:
public class FirstProgram{
public void first(){
String a = "hello";
}
}
public class SecondProgram{
public static void main(String[] args){
//i need to pass string here
}
}
Its not a good approach to take, but technically you can call the main method of the Second program and pass whatever argument you like
public class FirstProgram{
public void first(){
String a = "hello";
SecondProgram.main(new String []{a});
}
}
You can do this:
First.java:
public class First {
public static void main(String[] args) {
Second.main(args);
}
}
Second.java:
import java.util.Arrays;
public class Second {
public static void main(String[] args) {
Arrays.stream(args).forEach(System.out::println);
}
}
If you execute java First foo bar baz bat on the command line, you'll see that Second prints out "foo bar baz bat" in the console.
I don't recommend it.
You have to start your app by calling main in some program. Your First can invoke main in Second as shown, but it's First that starts the process.
Pretty confusing question.
But you can do smth like that:
public class FirstProgram{
public String first(){
String a = "hello";
return a;
}
}
public class SecondProgram{
public static void main(String[] args){
FirstProgram firstProgram = new FirstProgram();
String result = firstProgram.first();
}
}

Will this go in an infinite loop?

I am starting in java, so please bear with me if this sounds stupid.
I am trying the below code:
First.java
class First {
public static void main( String[] args ) {
First f = new First();
f.print();
}
private void print() {
System.out.println( "Hello, World!" );
}
}
Within the main function, i re-instantiate the same class as i need to call a non-static method from within the static main method.
While this works, i am wondering is this a good way to do it? And how many instances of f are created.
How can i make sure f would be a singleton.
Thanks
About the first question: Only one instance of the class First is created.
About the second question:
The singleton pattern involves using a private constructor and a factory method. You cannot create a new instance of First without using the getInstance factory method, and all calls to getInstance will return the same instance.
class First {
private static First instance = null;
private First() {}
public static First getInstance() {
if (instance == null) {
instance = new First();
}
return instance;
}
}
class Second {
public static void main(String[] args) {
First f = First.getInstance(); //Always the same instance of First.
}
}

Java: Can't access variable?

So i'm having a bit of a problem trying to compare two strings declared in the Main class. I've messed around with it and i really can't get it to work! The problem is in the if() statement where i compare the variables...
public class Main {
public String oldContent = "";
public String newContent = "";
public static void main(String[] args) throws InterruptedException {
Main downloadPage = new Main();
downloadPage.downloadPage();
oldContent = newContent;
for (;;) {
downloadPage.downloadPage();
if (!oldContent.equals(newContent)) { // Problem
System.out.println("updated!");
break;
}
Thread.currentThread().sleep(3000);
}
}
private void downloadPage() {
// Code to download a page and put the content in newContent.
}
}
the variables are instance members, whereas the for happens in a static method.
try moving the actual function to an instance method (not static), or conversely make the data members static as well.
You may use name of the object you have created (downloadPage ) to access to the parameters:
in the main finction use following instead of parameter names only:
downloadPage.oldContent
downloadPage.newContent
The variables are inside the Main object:
public static void main(String[] args) throws InterruptedException {
Main downloadPage = new Main();
downloadPage.downloadPage(); // Access them like you accessed the method
downloadPage.oldContent = downloadPage.newContent;
for (;;) {
downloadPage.downloadPage();
if (!downloadPage.oldContent.equals(downloadPage.newContent)) {
System.out.println("updated!");
break;
}
Thread.currentThread().sleep(3000);
}
}
Do consider using getters and setters instead of exposing the fields.
See non static/ static variable error

Categories

Resources