alaska
alaska

Reputation: 151

passing a scanner object to a method

If I pass a scanner object to a method, will the scanner scan from the beginning of the input or continued to scan for the remaining part of the input. Here is my code:

public class Test {
  public void test(Scanner sc) {
    System.out.println(sc.nextLine());
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    System.out.println(str);

    Test t = new Test(sc);
    t.test();
  }
}

// here is the input file:
1 2 3 4 
5 6 7 8
9 1 2 3

I have test this code on both on Windows and Linux, but I got two different result

The first result is in the method test, it print 5 6 7 8

the second result is difficult to understand, it print 1 2 3 4, still the first line of the input.

Is this related to the different version of Java, Can someone explain this for me, thank you!

Upvotes: 1

Views: 9526

Answers (3)

VirtualTroll
VirtualTroll

Reputation: 3091

I think your problem has to the break line.

A new line is defined in a different manner from one OS to another. If you print the value of

System.getProperty("line.separator");

You will see the value of the property is not the same in Windows and Linux.

I do not know where did you write your input file but it probably contain an OS specific line separator. When you run your program on another OS, you would end but a different result.

I suggest that you define the delimiters of your scanner file like this

sc .useDelimiter("\n|\r\n");

If I am not mistaken, \n represents the linux new line while \r\n represents the windows new line.

Upvotes: 0

Ravi Trivedi
Ravi Trivedi

Reputation: 2360

First of all, there is an error in your code >> Test t = new Test(sc). It uses parameterised constructor but I don't see any.

Q. if I pass a scanner object to a method, will the scanner scan from the beginning of
the input or continued to scan for the remaining part of the input ?

In Java, Objects are passed by Ref(reference to object heap address) not by values(as in primitive types). And that is why passing an Object to a function does not change the Object. The Object remains the same.

Regards, Ravi

Upvotes: 0

Patashu
Patashu

Reputation: 21793

The scanner is the same object in both methods - you're passing around references to the same scanner. So, it has no clue it's being used from a new place in the program - it will faithfully do the same thing no matter what code is using it if the same methods are called.

Upvotes: 1

Related Questions