0

I am having trouble getting my program to run interactively.

In one of the classes the System.in is being changed to read from a text file like so:

public class mainClass
{
    public static void main(String[] args)
    {
      ...
        try {System.setIn(new java.io.FileInputStream("foo.txt"));} 
        catch (java.io.FileNotFoundException e) {}
        Scanner sc = new Scanner(System.in);

        someClass instance = new someClass(sc);
      ...
    }
}

The problem I am having is in my other class. I don't know how to call point or reference to this same scanner.

EDIT:

Alright so my class accepts a scanner as an argument. Is there a way to call that variable in a method later on?

public someClass (Scanner sc)
{

}

public void test(String a)
{
   someClass.sc.nextLine();
}

When I try something like this I get an error saying it cannot find variable sc.

4

1 回答 1

3

You can't reference the same Scanner object unless you pass that reference to the other class or to some instance of it.

Scanner sc = new Scanner(System.in);
SomeClass instance = new SomeClass(sc);

the Scanner instance is passed as an argument to the constructor of SomeClass. You can save that reference in a variable and reuse it when you need.

于 2013-10-03T01:36:56.070 回答