2

I have this simple code where I'm trying to make two objects of a class and then call a function in that class but I'm getting

NoSuchElementException on the 42 line

i.e. where i declare the second object.

da

import java.io.*;
import java.util.*;

class da{
    int day, m, y;
    public da(){
        Scanner kb = new Scanner(System.in);
        day=kb.nextInt();
        m=kb.nextInt();
        y=kb.nextInt();
    }

    public void compare(da d){
        if(d.y>y){
            System.out.println("10000");
        }
        else if(d.y<y){
            System.out.println("0");
        }
        else{
            if(d.m>m){
            System.out.println((d.m-m)*500);
            }
            else if(d.m<m){
            System.out.println("0");
            }
            else{
                if(d.day>day){
                System.out.println((d.day-day)*15);
                }
                else if(d.day<=day){
                System.out.println("0");
                }
            }
        }
    }
}

Solution

public class Solution {

    public static void main(String[] args) {
        da issued = new da();
        da returned = new da();

        issued.compare(returned);

    }
}

The exception message I get is

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 da.<init>(Solution.java:8)
    at Solution.main(Solution.java:42)
SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
  • Are you passing in 6 ints on via standard in? Constructing each `da` requires 3 ints to be readable. – Andy Turner Jan 28 '16 at 16:19
  • _on the 42 line i.e. where i declare the second object._ But its impossible.. – SatyaTNV Jan 28 '16 at 16:21
  • How are you running this? You may be closing stdin without writing the values the scanner expects to read. The error is coming from `day=kb.nextInt();` because there are no more tokens available to read. – Jake Cobb Jan 28 '16 at 17:57
  • @Jens my input is ' 9 6 2015 ' and ' 6 6 2015 ' both in separate lines where all numbers are integers and are separated by a space and the two dates are on separate lines – Pranav Rastogi Jan 29 '16 at 09:04
  • @JakeCobb u are right... The program isn't taking the second date. I printed in the constructor and found that it takes the first but not the second. Probably a problem with the site I'm coding on. – Pranav Rastogi Jan 29 '16 at 09:08
  • @PranavRastogi you Need a `kb.nextLine()` after `y=kb.nextInt();` to consuble the end of line – Jens Jan 29 '16 at 09:21

0 Answers0