Java Method isn't resolved by stack object - java

I was trying to solve a problem named push at bottom of stack.
I got the recursion logic but the thing is, I have written a method pushAtbottom but the method is not recognized by the main method and I don't understand why. The error is 'Can not resolve pushAtbottom'
import java.util.Stack;
public class pushatbottom {
public static void main(String[] args) {
Stack<Integer> s =new Stack<>();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.pushAtbottom(6,s);
while(!s.isEmpty())
{
System.out.println(s.peek());
s.pop();
}
}
void pushAtbottom(int data,Stack<Integer> s)
{
if(s.isEmpty())
{
s.push(data);
}
int top=s.pop();
pushAtbottom(4,s);
s.push(top);
}
}

pushAtbottom is a method of your class, not of java.util.Stack. You need to declare it as static (i.e., static void ushAtbottom(int data,Stack<Integer> s)) and then pass the stack to it when calling it form main:
pushAtbottom(6, s);

Related

passing static variable value to another function

I have a static variable totalcontainer and I am assigning value to it in main method.
Now when I call it in another method it gives default value i.e. 0
The value of variable is not updating in second method.
import java.util.ArrayList;
public class abc {
static int totalContainer;
static ArrayList<Integer> count = new ArrayList<Integer>();
public static void main(String args[]) {
count.add(2);
count.add(10);
count.add(15);
count.add(6);
count.add(8);
totalContainer = count.size();
System.out.println(totalContainer);
}
public static float getCpu() {
int getcontainer = totalContainer;
System.out.println("in get cpu " + getcontainer);
return getcontainer;
}
}
I am calling method getCpu from another class and always getting value 0.
How can I use this variable value in another class?
This is a simple program to demonstrate the problem which i am facing.
If the getCpu() method is called from some other class, main method of class abc is not called.
If you need the count variable updated as in main method, define the implementation in a static block as below.
import java.util.ArrayList;
public class abc {
static int totalContainer;
static ArrayList<Integer> count = new ArrayList<Integer>();
static{
count.add(2);
count.add(10);
count.add(15);
count.add(6);
count.add(8);
totalContainer = count.size();
}
public static void main(String args[]) {
System.out.println(totalContainer);
}
public static float getCpu() {
float getcontainer = totalContainer;
System.out.println("in get cpu " + getcontainer);
return getcontainer;
}
}
If this is in a multi-threaded environment, it is possible that you call getCpu() before totalContainer is initialized. It looks like though as if it is a racing condition.
If you guarantee that the getCpu() is called after the completion of main method, then the value would be correct.
to test this, try this code:
System.out.println(totalContainer);
SwingUtilities.invokeLater(() -> getCpu());
What you can do since you are using multi-threading:
First initialize all you want, then start multithreading
or perform locking, to properly initialize

String cannot be converted to ArrayList<String> Error

Here is a program similar to the sinking battleship game from the book head first java. After compiling I am getting the error: "String cannot be converted to ArrayList Error" and ^ pointer point to the line I have two different files one with the main method and other a separate class. Whats wrong here.
Main method class
import java.util.Scanner;
public class SimpleDotComTestDrive{
public static void main(String[] args){
SimpleDotCom dot=new SimpleDotCom();
boolean repeat=false;
String[] locations={"2","3","4"};
dot.setLocationCells(locations); //^ where compiler points the error
Scanner input=new Scanner(System.in);
System.out.println("Lets Start");
while(repeat==false) {
System.out.println("Type your guess");
String userGuess=input.nextLine();
String result=dot.checkYourSelf(userGuess);
System.out.println(result);
if(result=="kill") {
repeat=true;
break;
}
}
} //close main
} //close test class
Separately saved class which is part of this program:
import java.util.ArrayList;
public class SimpleDotCom {
private ArrayList<String>locationCells;
public void setLocationCells(ArrayList<String> locs) {
locationCells=locs;
}
public String checkYourSelf(String userGuess) {
String result="miss";
int index = locationCells.indexOf(userGuess);
if(index>=0) {
locationCells.remove(index);
if(locationCells.isEmpty()) {
result="kill";
}
else {
result="hit";
}
}
return result;
} //close check yourself method
} //close simple class
You are getting the error because setLocationCells() method accepts an ArrayList<String> and you are passing it a String Array by doing:
dot.setLocationCells(locations);
You should either replace your method to accept String[] instead of ArrayList<String> or change your code as follows:
dot.setLocationCells(new ArrayList<String>(Arrays.asList(locations));
You cannot have String[] locations={"2","3","4"}; and then parse it to the method setLocationCells(ArrayList<String> locs){ that requires the ArrayList.
So, there are more ways:
Convert the array to list with: new ArrayList<String>(Arrays.asList(locations);
Define the ArrayList instead:
ArrayList<String> list = new ArrayList<String>() {{
add("2");
add("3");
add("4");
}};
Change your method at all:
public void setLocationCells(String[] locs){
Collections.addAll(locationcells, locs);
}

Error: Main method not found in class MovieDatabase [duplicate]

This question already has answers here:
Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args) [duplicate]
(5 answers)
Closed 8 years ago.
Error: Main method not found in class MovieDatabase, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
import java.io.FileInputStream;
import java.util.Scanner;
import java.util.Arrays;
public class MovieDatabase {
private int[] analysis;
//creating the contructor
public MovieDatabase(String file){
analysis = new int[2015];
this.load(file);
}
//uses the load(String file) method from downstairs to do all of the work
public void load(String file){
Scanner theScanner = null;
try{
//inputing the into the scanner
theScanner = new Scanner(new FileInputStream(file));
}
catch(Exception ex){
ex.printStackTrace();
}
// as long as the scanner has another line
while(theScanner.hasNextLine())
{
String Line = theScanner.nextLine();
//make an array called split and allocated different elements based on a seperation of ##
String split[] = Line.split("##");
int year = Integer.valueOf(split[1]);
analysis[year] ++;
}
}
//print out the array in the synchronous format
public void print(){
System.out.printf("%1$-30s %2$10s %3$10s %4$10s ", "Year", "Occurances", "", "");
//go through the array
for (int i =0;i < analysis.length ;i++ ) {
if(analysis[i] >0){
for (int j =i;j < analysis.length ;i++ ){
System.out.printf("%1$-30s %2$10s %3$10s %4$10s ", j, analysis[j], "", "");
}
}
}
}
}
How do I fix this error message?
Ive read other similar questions but just say to make the classes public. Mine are public.
main() method in Java is an standard method which is used by JVM to start execution of any Java program. main method is referred as entry point of Java application which is true in case of core java application
You have missed it. Add following main() method
public static void main(String[] args) {
MovieDatabase db = new MovieDatabase("file/path/goes/here");
db.print();
}
In the Java programming language, every application must contain a
main method whose signature is:
public static void main(String[] args)
As the error suggests, if its non FX project, just define something like:
public static void main(String args[]) {
...
}
Or else change you class definition so it extends Application, something like:
public class MovieDatabase extends Application
To invoke any application JVM need main() method, and which should have following access specifiers and modifiers,
public static void main(String args[])
public - It should be accessible to all
static - JVM not able to create instance of your class so method should be static
void - method not returning anything
For each java application main method is entry point, so your application should have atleast one main method to start execution of application.
It's because you have forgot to add the main method. The error clearly says:
please define the main method as: public static void main(String[]
args)
So add the main:
public static void main(String[] args) {
MovieDatabase m = new MovieDatabase("Your File Path");
m.print();
}

There are no main classes found

When I play it in NETBEANS IDE 8.0 it keeps saying there is no main class even though I added the main class already?
Need help can't understand.
PS. If I delete the static in magic() it blocks the magic() in main.
package fibotail;
import java.util.Scanner;
public class Fibotail {
public static int fibo(int control, int currentValue, int previousValue) {
if (control < 2) {
return currentValue;
}
return fibo(control - 1, currentValue + previousValue, currentValue);
}
public static void magic() {
String cCharacter;
do {
System.out.println("Input here: ");
int something = new Scanner(System.in).nextInt();
for (int i = 1; fibo(i, 0, 1) <= something; i++) {
System.out.println(fibo(i, 0, 1));
}
do {
System.out.println("Do you want to try again? ");
cCharacter = new Scanner(System.in).next();
} while (!(cCharacter.equals("y") || cCharacter.equals("Y") || cCharacter.equals("N") || cCharacter.equals("n")));
} while (cCharacter.equals('y') || cCharacter.equals('Y'));
}
public static int main(String args[]) {
magic();
return 0;
}
}
Return type should be void, not int:
public static void main(String args[]) { ... }
The JVM looks for the exact signature of the method.
When you run your project you would get:
Error: Main method must return a value of type void in class MainTest, please
define the main method as:
public static void main(String[] args)
In other languages than java, where main returns int (such as C and C++) the return code of main becomes the exit code of the process, which is often used by command interpreters and other external programs to determine whether the process completed successfully.
But java needs void as the return value. (Java internal architecture)
If you reaaly need to return a value just use the following:
System#exit(int)
To enable your program quit with a specific exit code which can be interpreted by the operating system.
Your main() method must have return type void
public static void main(String[] args){
}
Not int or other.
main() method is the entry point of your program and JVM is looking exact main() method.
You have to change your code a little bit. It should be:
public static void main(String args[])
The return type of main method is void

java question to decide who called this method

I have the following scenario where
both testOne() and testTwo calls same callMe() method.
How do I decide inside callMe() method who called callMe().
public void testOne(){
callMe();
}
public void testTwo(){
callMe();
}
public void callMe(){
System.out.println("I was called by following method."+methodName);
}
Any sort of help is appreciated.
Any solution that has you generating a stacktrace and looking at the second frame is one that is going to lead to pain - what you are essentially doing is bypassing the idea of passing what a function needs to it in order for the function to do it's work.
If you need the name of the caller method, then just pass it as a parameter. If you need some other piece of data to decide what to do in the callMe() method, pass it (as a boolean, int, etc.).
It will confuse other developers working on your code why callMe() has what are essentially secret parameters.
public void testOne(){
callMe("testOne");
}
public void testTwo(){
callMe("testTwo");
}
public void callMe(String methodName){
System.out.println("I was called by following method."+methodName);
}
My best answer is to query the stack trace.
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String previousMethodName = null;
for (int i = 0; (i < stackTrace.length) && (previousMethodName == null); i++)
{
if (stackTrace[i].getMethodName().equals("callMe") && (i < stackTrace.length - 1))
{
previousMethodName = stackTrace[i + 1].getMethodName();
}
}
if (previousMethodName != null)
{
System.out.println("Previous method = " + previousMethodName);
}
sorry, i meant to answer your question and not comment :( so here it is
i think this already answered question may help you out: Get current stack trace in Java
The simplest approach is to use a parameter
public static void testOne(){
callMe("testOne");
}
public static void testTwo(){
callMe("testTwo");
}
public static void callMe(){
System.out.println("I was called by following method."+methodName);
}
However, you can use the call stack.
public static void callMe(){
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
System.out.println("I was called by following method."+methodName);
}

Categories