[英]java.lang.StringIndexOutOfBounds error
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));
}
}
I get this error when i run the program and i don't understand why. 我在运行程序时收到此错误,但我不明白为什么。 All i want to do is print the 7th character.
我要做的就是打印第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)
You are using next()
, which only reads the hello
the first time you call it. 您正在使用
next()
,它仅在您首次调用hello
时读取。 You would get the world
if you called next()
again. 如果再次调用
next()
,将会获得world
。
Use nextLine()
if you want to read hello world
in one go. 如果要一次性阅读
hello world
,请使用nextLine()
。
You can refer to the documentation to read more about the different methods available on the Scanner
class. 您可以参考文档以阅读有关
Scanner
类上可用的不同方法的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.