-1
public void menu()
 int option=0;
    Scanner b= new Scanner(System.in);
    while (true){

        System.out.println("Your options is:");

        option=b.nextInt();
        b.nextLine();
        if(option==1)
            add();
        else ...

I make the call of function add in my main,it takes input values the way it should but when it comes again in the while,everything crashes.

> public void add(){
>       int id;float grade; String name;
>       Scanner z= new Scanner(System.in);
>     //taking values for the 3 vars
>     Student s= new Student(id,name,grade);
>       c.addC(s);
>       z.close();}

addC is in the Ctrl package and it looks kind of like this

  public void addC(Student s){
        if(findById(s.getId()) != null)
        {System.out.println("Err!Duplicate id!/n"); 
        }else
                if(s.getGrade()>10)
                        System.out.println("Err!Grade bigger than 10!/n");  
                else{  
                    x.push(s);}

push() is there because I try to implement it on a stack.The error line is option=b.nextInt() I feel like It's my fault but as a java-starter I can;t figure it out by myself,any ideeas?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Matt
  • 484
  • 5
  • 15
  • WHat is the exception you're getting? – Andrew Oct 23 '13 at 15:32
  • 2
    It's not entirely easy to see what's going on given only random bits of code. Posting an [SSCCE](http://sscce.org/), that we can just run and see the error for ourselves, would be preferred. – Bernhard Barker Oct 23 '13 at 15:35
  • Tenner bet its a `NoSuchElementException`. – christopher Oct 23 '13 at 15:36
  • First, your use of braces is quite irritating: one time you use them for one-line blocks and another time you don't use any. To keep bugs related to that at a minimum, please use a consistent style. Second, a bunch of variables are not defined or omitted, e.g. `c`, `x`, etc. - all this makes it hard if not impossible to understand what your code actually does. – Thomas Oct 23 '13 at 15:38
  • @Matt can you mark the line which is indicated by the exception's stack trace? – Thomas Oct 23 '13 at 15:39

1 Answers1

2

The problem is that you use two Scanners on the same stream: System.in.

See also: How to use multiple Scanner objects on System.in?

edit: Is it possible to reuse the first Scanner? That way you can close the Scanner at the proper time, and not after the first student input.

Community
  • 1
  • 1
ljgw
  • 2,751
  • 1
  • 20
  • 39