• Post Reply Bookmark Topic Watch Topic
  • New Topic

Code not working. Exact same code works on the same class.  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to make a calculator. Please fix the error I am a beginner and I do not understand anything what the compiler says. The problem is highlighted with the comment beside it.

package apples;
import java.util.Scanner;

class apples{
public static void main(String args[]){

tuna obj = new tuna();
obj.veiws();

}
// the method returns a value. It works fine.
public int getf(){
int fnum;
Scanner srij = new Scanner(System.in);
System.out.println("Enter 1st number");
fnum = srij.nextInt();
srij.close();
return fnum;
}
//The following is same as above one. But is not working
public int gets(){
int snum;
System.out.println("Enter 2nd number");
Scanner srija = new Scanner(System.in);

snum = srija.nextInt();     //  <-- here is the error

srija.close();
return snum;
}
}

and the compiler says
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at apples.apples.gets(apples.java:24)
at apples.add.jod(add.java:8)
at apples.tuna.veiws(tuna.java:19)
at apples.apples.main(apples.java:8)

I have not included any code of classes. But I can if needed.

I replaced the line with snum = 25. And it worked.
 
Ranch Foreman
Posts: 3068
37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Closing that Scanner also closes (I believe) System.in, so any later call will cause problems.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dave Tolls wrote:. . . Closing that Scanner also closes (I believe) System.in . . .
You believe correctly. It is necessary to learn which of Eclipse's warnings to disregard. When it warns about a resource leak, it is correct, but you need to keep Scanners pointing to System.in open for ever. In fact you shou‍ld only use one Scanner to read everything from System.in. . . . And to think you can buy books which say you must close a Scanner reading for System.in

srijan poudel: welcome to the Ranch
 
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
srijan poudel: Welcome to the Ranch!

About your post: please UseCodeTags (that's a link) when posting code.  It will automatically add line numbers which you can then refer to in your post.  Also, it makes the code much easier to read.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!