简体   繁体   English

java.lang.StringIndexOutOfBounds错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM