Harry Tong
Harry Tong

Reputation: 259

New to java - Exception in thread “main” java.util.NoSuchElementException

I'm new to Java - I've looked but can't seem to find whats wrong with this code.

import java.util.*;

class MyClass {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please input grade");
        int grade = scan.nextInt();
        String gradeLevel = "Error";

        if ((grade > 100) || (grade < 0)) {
            System.out.println("Sorry please put a number between 0-100");
        } else if (grade > 90) {
            gradeLevel = "A";
        } else if (grade > 75) {
            gradeLevel = "B";
        } else if (grade > 49) {
            gradeLevel = "C";
        } else {
            gradeLevel = "F";
        }
        System.out.println("This student recieved " + gradeLevel + " for his/her grade");
    }
}

This is the error i'm getting:

> Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at MyClass.main(Main.j`

Upvotes: 0

Views: 1024

Answers (3)

likeToCode
likeToCode

Reputation: 852

Initially it felt strange why you are getting this error, because I don't get it in my Eclipse IDE, but finally figured it out, I guess you should be using online IDE or something. You have to supply the input before starting the program. See the below screenshots and how I supply the value.

enter image description here

enter image description here

enter image description here

Upvotes: 0

noyal_asok
noyal_asok

Reputation: 384

Code is working perfectly fine in Eclipse IDE, I'm using, with the most of the inputs I'm giving. I think you just look for whether System.in is available by using

System.out.println(System.in.available());

or use a generic function like scan.next();

Note: just close resources like Scanner classes, even though it will not cause any errors

Upvotes: 2

K.Suthagar
K.Suthagar

Reputation: 2306

What you are seeing is an exception because System.in has an "end of file" status. Here you are trying to get Input before you type.

  1. Just try scan.next () to resolve.

  2. Please use a better IDE to resolve the expectations automatically.

Upvotes: 0

Related Questions