Question

I am working on a project where I need to pass a scanner from the static main method to a non-static method from a text file read by the scanner and have it return a float. So far I have:

public class Calculator extends Stack{
public static void main (String []args) {
    Scanner s = new Scanner(System.in);
    try
    {
        s = new Scanner(new FileInputStream("numbers.txt"));
        float z = calculate (s);

    } 

Then in my calculate method its declaration is just public float calculate(Scanner s){ I know similar questions have been asked many times but I am just not getting it. What is throwing me off is that there is no new object being created like nodes. Thank you.

Was it helpful?

Solution

You need to create an instance of the class. As the calculate() method is non-static, you need to invoke it on an instance of the class.

public class Calculator extends Stack{
public static void main (String []args) {
    Scanner s = new Scanner(System.in);
    Calculator c = new Calculator();
    try
    {
        s = new Scanner(new FileInputStream("numbers.txt"));
        float z = c.calculate (s);

    } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top