Life Universe and Everything

在这里输入图像描述

I am new to CodeChef and I am getting the following output as error on CodeChef (An online platform for coding) editor and I am not able to submit my code.

I want to ask

1)Is My Approach towards the problem right and

2)When this error come?

3)Why I am getting compilation error?

MyApproach:

import java.util.Scanner;
class Prog1 {
    public static void main(String[] args) throws java.lang.Exception {
        int a = 0;
        Scanner sc = new Scanner(System. in );
        int t = 1;
        while (t != 0) {
            a = sc.nextInt();
            if (a != 42) System.out.println(a);
            else t = 0;
        }
    }
}

In my eclipse editor output shown is:

34
34
53
53
42

But I am getting following exception on Codechef editor:

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 Prog1.main(Main.java:15)

Thankx in advance


I'm guessing that the issue is that your Scanner is attempting to read text when none exists. Try the Scanner's hasNextInt() method:

int a = 0;
Scanner sc = new Scanner(System.in);
boolean t = false;
while (!t) {
    if (sc.hasNextInt()) {
        a = sc.nextInt();
        if (a != 42)
            System.out.println(a);
        else
            t = true;
    }
}

Also, you should be using a boolean instead of an int (for t ).


You are missing brackets for the if statement.

    while(t!=0)

   {

     a=sc.nextInt();

     if (a != 42) {
         System.out.println(a);
     }
     else {
         t=0;
     }
   }

This will not print 42 when reached however, you would need to add the system print call again for when a does equal 42:

if (a != 42) {
         System.out.println(a);
     }
     else {
         System.out.println(a);
         t=0;
     }
链接地址: http://www.djcxy.com/p/96120.html

上一篇: Java.util.NoSuchElement异常

下一篇: 生命的宇宙和一切