【问题标题】:Java Splitting Strings and Applying A MethodJava拆分字符串并应用方法
【发布时间】:2017-03-21 21:30:06
【问题描述】:

我正在编写一个 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;
        }
    }
}

【问题讨论】:

    标签: java arrays methods split


    【解决方案1】:

    检查内联 cmets:

    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”交互
    • 编辑:对不起,我错过了一个右括号。非常感谢
    【解决方案2】:

    正如 String.split();您可以定义一个正则表达式,例如“”,然后返回一个 String[] 的返回数组,用于在输入上拆分的所有子字符串

    String split

    示例

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

    您可以通过同样的方式测试其他内容,例如“、”、“。” “;” “:”等

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2016-03-23
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 2014-05-27
      相关资源
      最近更新 更多