在在线编译器上而不是在命令提示符下面临运行时错误

facing runtime error on online compiler and not on command prompt

我不明白为什么这个 java 代码在命令提示符下工作正常,而不是在在线编译器中工作,并且出现运行时错误。 我试图在网上找出原因,但没有找到合适的答案。

其获取运行时错误-

       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 head.main(Main.java:9)

代码是-

       import java.util.*;


       class head
         {
       public static void main(String arg[])
        {
       Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int c1=0,c2=0;
        int i;
        while(n>0)
        {
        int l=sc.nextInt();
        String str=sc.next();

        for(i=0;i<l;i++)
        {
        char ch=str.charAt(i);
        if(ch=='i'||ch=='I') 
        c1++;
          if(ch=='y'||ch=='Y')
         c2++;
         } 
         if(c1>0)
         System.out.println("INDIAN");
        else if(c2>0)
        System.out.println("NOT INDIAN");
        else 
        System.out.println("NOT SURE");
        c1=0;
        c2=0;
        n--;
        }
       }
     } 

您没有检查扫描仪是否有更多数据要扫描,这就是您出现异常的原因。

参见下面 Scanner 中定义的 throwError 方法。

// If we are at the end of input then NoSuchElement;
// If there is still input left then InputMismatch
private void throwFor() {
    skipped = false;
    if ((sourceClosed) && (position == buf.limit()))
        throw new NoSuchElementException();
    else
        throw new InputMismatchException();
}

在评论中说当输入结束时调用它。

Scanner 的正确用法总是如下所示

Scanner scan = new Scanner(inputstream);

while(scan.hasNext()) {
    //read data
}

这与读取文件相同,每次尝试读取时都必须检查 EOF(文件结尾)。

在您的代码中,可以像下面这样应用更正。

import java.util.*;

class head {
    public static void main(String arg[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int c1 = 0, c2 = 0;
        int i;
        while (n > 0) {
            //check for EOF
            if(!sc.hasNext()) {
                break;
            }
            int l = sc.nextInt();
            String str = sc.next();

            for (i = 0; i < l; i++) {
                char ch = str.charAt(i);
                if (ch == 'i' || ch == 'I')
                    c1++;
                if (ch == 'y' || ch == 'Y')
                    c2++;
            }
            if (c1 > 0)
                System.out.println("INDIAN");
            else if (c2 > 0)
                System.out.println("NOT INDIAN");
            else
                System.out.println("NOT SURE");
            c1 = 0;
            c2 = 0;
            n--;
        }
    }
}