import java.util.Scanner;
public class s
{
public static void main(String[] args)
{
Scanner input=new Scanner (System.in);
String string=input.next();
System.out.println(string.charAt(7));
}
}当我运行这个程序时,我会得到这个错误,我不明白为什么。我只想打印第七个字。
PS E:\Users\adiad\Documents\Scuola\Informatica\Madeo\Pratica> java s
hello world
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.base/java.lang.StringLatin1.charAt(Unknown Source)
at java.base/java.lang.String.charAt(Unknown Source)
at s.main(s.java:9)发布于 2018-05-29 19:07:32
您使用的是next(),它只在第一次调用hello时才读取它。如果您再次调用world,您将得到next()。
如果您想一次性阅读nextLine(),请使用hello world。
您可以参考提交给文件阅读更多关于Scanner类上可用的不同方法的信息。
https://stackoverflow.com/questions/50591260
复制相似问题