编译错误在运行给定的程序时显示。

huangapple go评论62阅读模式
英文:

Compilation error is displayed while running the given program

问题

我刚开始在Codeforces上练习竞技编程。在解决一个问题时遇到了一个问题。显示了编译时错误:

import java.util.*;
public class A71
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int n ;
        n=sc.nextInt();
        String a[] = new String[n];
        for(int i=0;i<n;i++)
        {
            a[i]=sc.nextLine();
        }
        for(int i=0;i<n;i++)
        {
            int l=a[i].length();
            System.out.println(a[i].charAt(0)+""+(l-2)+""+a[i].charAt(l-1));
        }
    }
}

显示的错误如下:

java.lang.StringIndexOutOfBoundsException: String index out of range: 0
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
	at java.base/java.lang.String.charAt(String.java:693)
	at A71.main(A71.java:17)

Runtime error: exit code is 11
英文:

I just started practicing competitive programming on codeforces.I faced a problem in solving a question. it is showing compile time error

import java.util.*;
public class A71
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int n ;
        n=sc.nextInt();
        String a[] = new String[n];
        for(int i=0;i&lt;n;i++)
        {
            a[i]=sc.nextLine();
        }
        for(int i=0;i&lt;n;i++)
        {
            int l=a[i].length();
            System.out.println(a[i].charAt(0)+&quot;&quot;+(l-2)+&quot;&quot;+a[i].charAt(l-1));
        }
    }
}

The error which is displayed is below

java.lang.StringIndexOutOfBoundsException: String index out of range: 0
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
	at java.base/java.lang.String.charAt(String.java:693)
	at A71.main(A71.java:17)

Runtime error: exit code is 11

答案1

得分: 0

正如Stultuske在评论中指出的那样,你之所以收到这个错误是因为访问了一个空字符串。尝试在循环中用sc.next()替换sc.nextLine()。

英文:

As Stultuske pointed out in the comments, you receive this error due to access on an empty String. Try to replace sc.nextLine() with sc.next() in a loop

huangapple
  • 本文由 发表于 2020年5月5日 16:25:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/61608853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定