在字符串拆分和分配给新变量时在终端上提供输入时出现异常(arrayOutofboundException)

问题描述 投票:0回答:1
public class String_spilt_assigning {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
            System.out.println("Enter a string: ");
        String A = sc.next();
        
        System.out.println(A.length());
        String[] B = A.split(" ");

        String C = B[0];
        String D = B[1];

        System.out.println(C);
        System.out.println(D);
        
    }
}

输出:

输入字符串:

hello world
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
    at hackerrank_problems/com.hackerrank_problems.soln.String_spilt_assigning.main(String_spilt_assigning.java:15)

当我在代码本身中提供一个字符串时,它会拆分并分配给变量 C,D 并显示输出 但是当我要求用户输入一个字符串时,它显示了前面提到的错误......

java arrays string split
1个回答
0
投票

使用

sc.nextLine()
代替
sc.next()

sc.next()
只会返回第一个标记,即“hello”

sc.nextLine()
将返回整个字符串,直到出现新行,即“hello world”

© www.soinside.com 2019 - 2024. All rights reserved.