Java 错误:无法解析方法 split()

我正在尝试将用户输入输入到字符串数组中并想使用该string.split()方法,但出于某种原因,我的 IntelliJ 告诉我,它无法解析方法“split()”。


package com.Practice;

import java.util.Scanner;


public class Main {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        String input = sc.nextLine();


        String[] splittedString = input.split();

    }

}

我不认为我的代码有问题,可能是我的 IDE 或 Java 版本有问题,但我不是这方面的专家。当我尝试运行该程序时,它抛出了这个错误:


Error:(10, 40) java: no suitable method found for split(no arguments)

    method java.lang.String.split(java.lang.String,int) is not applicable

      (actual and formal argument lists differ in length)

    method java.lang.String.split(java.lang.String) is not applicable

      (actual and formal argument lists differ in length)


FFIVE
浏览 682回答 3
3回答

小唯快跑啊

Java 确实没有不String#split带参数的方法。您需要通过正则表达式拆分字符串,例如\\s(这意味着通过空格拆分):String[] splittedString = input.split("\\s");

慕哥6287543

正如其他一些答案中提到的,String.split()在 Java 中需要输入,如果您打算将某些内容应用于每个字符或创建一个字符数组,例如您需要迭代。private String myCoolString = "myCoolString";private char[] chars = new char[myCoolString.length()];//array of primitive charsfor( int i = 0; i < myCoolString.length();i++){&nbsp; &nbsp; chars[i] = myCoolString.charAt(i);}// List of boxed Characters (Java 8+, the above can be used to do this too)List<Character> charList =&nbsp; &nbsp; &nbsp; &nbsp; myCoolString&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .chars()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(e->(char)e)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());

当年话下

您需要在split方法中添加一个参数。在这里检查拆分方法public class Main {public static void main(String[] args) {&nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; String input = sc.nextLine();&nbsp; &nbsp; String[] splittedString = input.split(" ");}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java