1

I have an exercise that gives me x number of inputs and I have to create binary tree with it: https://www.e-olymp.com/en/problems/3096
I have tried this following code

Scanner inp=new Scanner(System.in);
        while(true){
            String i=inp.next();
            int n=Integer.parseInt(i);
            thetree.addNode(n,"Boss");
        }

But when i click ctrl+z it gives me errrors like
Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:907) at java.util.Scanner.next(Scanner.java:1416) at BinaryTree.b1.main(b1.java:41) How can I get input until ctl+z just like in c++?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Papa Joh
  • 33
  • 7
  • 1
    take look at this post: http://stackoverflow.com/questions/7209110/java-util-nosuchelementexception-no-line-found – JHDev Dec 03 '16 at 08:12
  • @esprittn thanks it worked! – Papa Joh Dec 03 '16 at 08:21
  • Just for the record: in case you found my answer helpful you might still accept it. Thanks for considering... – GhostCat Dec 03 '16 at 18:38
  • @GhostCat sorry but page had too many functions there,so i couldn't read all of them. – Papa Joh Dec 04 '16 at 14:44
  • I am not sure what you are telling me here. The point is: when you want to get into coding, than that will need time. For example: time to study the classes you intend to use. When you are serious about the things you do, then you should be serious about **understanding** the stuff you intend to use. Otherwise, you just walk from one "strange problem" to the next. – GhostCat Dec 04 '16 at 15:12

1 Answers1

1

You want to use one of the many versions of hasNext methods that the scanner provides to you.

See the corresponding hasNext() javadoc:

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan.

next() just tries to read from the scanner, and if nothing is there (what happens when ctrl-z is pressed), that will fail!

GhostCat
  • 137,827
  • 25
  • 176
  • 248