View Single Post
  #3 (permalink)  
Old 12-11-2007, 06:35 AM
hey hey is offline
Member
 
Join Date: Dec 2007
Posts: 21
hey is on a distinguished road
Quote:
Originally Posted by staykovmarin View Post
You are getting that problem because InputInt() is static. That means that everything declared in that method is static, so it will be the same throughout execution. More on this: Understanding Instance and Class Members (The Java™ Tutorials > Learning the Java Language > Classes and Objects)

You are closing the Scanner stream in the InputInt()
Code:
in.close();
The problem is that once you close it, the stream is dead, so the next time you call it, it cant read from the command line (thats why it works on the first call of InputInt() but not the second.

One solution is to remove the in.close() and it will work fine. Another solution is the create an instance of the Input class and make InputInt non static:

Code:
import java.util.Scanner; class Min { public static void main(String[] args) { int x = 0, y = 0, z = 0, f = 0, i = 0; Input input = new Input(); x = input.InputInt(); System.out.println(x); y = input.InputInt(); System.out.println(x); } } class Input { public int InputInt() { int x = 0; Scanner in = new Scanner(System.in); // reads int from the console // and stores into x x = in.nextInt(); // notice that now you can close the stream, since the method is non static in.close(); return x; } }
Thanks a lot. I just removed in.close(), and it worked, on the other hand it doesn't work, when I make non-static (I just copied your code)
Reply With Quote