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)
最佳答案
您正在使用next()
,它仅在您第一次调用它时读取hello
。如果再次调用 next()
,您将获得 world
。
如果您想一次性读取 hello world
,请使用 nextLine()
。
您可以引用to the documentation详细了解 Scanner
类上可用的不同方法。
关于java.lang.StringIndexOutOfBounds 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50591260/