gpt4 book ai didi

java - 尝试按空格分割用户输入字符串

转载 作者:行者123 更新时间:2023-12-01 17:47:29 25 4
gpt4 key购买 nike

尝试拆分一个字符串并输出用户输入的倒数第二个单词,但 .split() 似乎只将单个字符串输出到数组中,因此它不起作用?

import java.util.*;

public class Random_Exercises_no60 {

public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.next();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
System.out.println("Penultimate word " + words[words.length - 2]);
}
}

最佳答案

问题不在于 split 方法,而是您应该使用 nextLine 而不是 next:

String sentence = sc.nextLine();

关于java - 尝试按空格分割用户输入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53500280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com