英文:
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<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));
}
}
}
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论