Java拆分字符串并应用方法

Java拆分字符串并应用方法,java,arrays,methods,split,Java,Arrays,Methods,Split,我正在用java编写一个代码,该代码将一个单词内的一个随机字母与该单词内的另一个随机字母交换 我需要将此代码应用于整个字符串。我遇到的问题是,我的代码无法识别空白,因此每个字符串运行一次方法,而不是每个单词运行一次。如何拆分输入字符串并将该方法分别应用于每个单词。这是我到目前为止所拥有的 import java.util.Scanner; import java.util.Random; public class Main { public static void main(Strin

我正在用java编写一个代码,该代码将一个单词内的一个随机字母与该单词内的另一个随机字母交换

我需要将此代码应用于整个字符串。我遇到的问题是,我的代码无法识别空白,因此每个字符串运行一次方法,而不是每个单词运行一次。如何拆分输入字符串并将该方法分别应用于每个单词。这是我到目前为止所拥有的

import java.util.Scanner;
import java.util.Random;

public class Main {
    public static void main(String[] args {
        Scanner in=new Scanner(System.in);
        System.out.println("Please enter a sentance to scramble: ");
        String word = in.nextLine();
        System.out.print(scramble(word));
    }
    public static String scramble (String word) {
        int wordlength = word.length();
        Random r = new Random();
        if (wordlength > 3) {
            int x = (r.nextInt(word.length()-2) + 1);
            int y;
            do {
                y = (r.nextInt(word.length()-2) + 1); 
            } while (x == y);
            char [] arr = word.toCharArray();
            arr[x] = arr[y];
            arr[y] = word.charAt(x);
            return word.valueOf(arr);
        }
        else {
            return word;
        }
    }
}

如String.split()中的destriped;您可以为实例“”定义一个regrex,然后为输入上拆分的所有子字符串返回字符串[]的返回数组

示例

String in = "hello world";
String[] splitIn = in.split(" ");

您可以使用相同的方法测试其他内容,例如“,”;“:”等检查内联注释:

import java.util.Scanner;
import java.util.Random;

public class Main {
  public static void main(String[] args)
       {
          Scanner in=new Scanner(System.in);
          System.out.println("Please enter a sentance to scramble: ");
          String word = in.nextLine();


          //Split your input phrase
          String[] wordsArray = word.split(" ");
          //For each word in the phrase call your scramble function
          // and print the output plus a space
          for (String s : wordsArray){
              System.out.print(scramble(s) + " ");
          }

       }
  public static String scramble (String word) {
    int wordlength = word.length();
    Random r = new Random();
  if (wordlength > 3) {
    int x = (r.nextInt(word.length()-2) + 1);
   int y;
   do {
    y = (r.nextInt(word.length()-2) + 1); 
   } while (x == y);
   char [] arr = word.toCharArray();
   arr[x] = arr[y];
   arr[y] = word.charAt(x);
   return word.valueOf(arr);
  }
  else {
    return word;
  }
  }
}

在我的代码中添加这一点会导致该方法出现错误,并且无法编译。我是否需要将该方法更改为与“s”而不是“word”EDIT交互:很抱歉,我缺少一个右括号。多谢各位