Java-单词扰码器[保留首字母和尾字母]

时间:2019-03-13 00:28:28

标签: java arrays substring

我的任务是编写一个程序,以便在保留一个首字母和最后一个字母相同且仅交换两个字母的同时对单词进行加扰,然后提示用户是否愿意继续操作。

示例:userInput = bacon | Output = bcaon

我已经附上了我的程序的想象,可能有几个问题,但是就目前情况来看,由于图像中的错误,我无法真正运行它。我真的很困惑,因为我得到了一名助教来帮助我完成这项任务,他们似乎认为这肯定会起作用,但是正如您所看到的那样。

如果有人能告诉我究竟是什么问题以及原因,我将不胜感激。而且,如果您要添加任何东西来使该程序正常运行,我也将非常感谢,但是最重要的是,我只是想了解问题所在和原因。

import java.util.Scanner;
import java.util.Random;
public class FreeStyle {

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);                        // Importing and initializing keyboard to 'in'
    System.out.println("Please enter a word to be scrambled"); // Asking user for a word
    String word = in.next();                               // Initializing the user's input 
    System.out.println(swapLetters(word));                    

    System.out.println("Would you like to enter another word? y/n");
    String answer = in.next();
    boolean userDone = true; //Using a Boolean statement to ask the user if they are done enter words or not
    while (userDone) {

        if (answer.equals('y')) {
            System.out.println("Please enter a new word");      //Ask user for new word to scramble
            word = in.nextLine();                                   //New initialization for 'word'
        } else if (answer.equals('n')) {                            //If user types 'n', loops then breaks because while(userDone) is false
            userDone = false;
        } else {
            System.out.println("Invalid input, please enter more than 3 letter words."); // The logic doesn't flow or apply to words that are less than 4 letters, so this catches that error and notifies the user
        }
    }
}

private static String swapLetters(String word) { //Private method used for the program only, no need to involve the user

    Random r = new Random(); //Using random instead of math floor
    //int arraysize = word.length();
    int a = r.nextInt(word.length()-2)+1; 
    int b = r.nextInt(word.length()-2)+1;
    //String word2 = word.substring(a, a+1);    
    String word2 = word.substring(0, a) + word.charAt(b)+word.substring(a+1, b)+word.charAt(a)+word.substring(b+1);
    return word2;
}

3 个答案:

答案 0 :(得分:1)

您假设两个随机数ab的属性为a < b。如果a >= b怎么办?然后word.substring(a+1, b)将抛出一个error

要解决此问题,只需确保维护a < b(重新生成,交换等)。

但是可以肯定的是,您的代码中不仅存在此错误。例如,使用next(),将Stringchar进行比较,使用错误的换行符,不去除换行符等等。您可能想在代码中添加一些打印语句,以查看实际发生的情况。

答案 1 :(得分:1)

几点:

  1. 为什么不使用已经完全完成的工作来完成您要尝试的工作-Collections.shuffle?查看代码中的注释以了解其工作原理。
  2. 您不能在字符串和字符之间使用equals()(''是字符,“”是字符串)。简单修复-只需将“ y”放入“ y”,与“ n”相同。
  3. 我从一开始就重构了用于获取用户输入的代码,然后将其争用为另一个方法,因此我们可以再次使用它-getInputAndScramble
  4. 最后,我使用了do-while循环来保持循环,直到用户使用“ n”字母停止循环为止。

请在代码中查看我的评论,希望可以清除所有问题。

public class Scrambler {

    public static void main(String[] args) {

        boolean userDone = true; 
        String word;

        Scanner in = new Scanner(System.in);                      
        getInputAndScramble(in); //Extracted method to get Scanner input and scramble

        do {
            System.out.println("Would you like to enter another word? y/n");
            word = in.next();
            while (userDone) {
                if (word.equals("y")) {
                    getInputAndScramble(in);
                    break;
                } else if (word.equals("n")) {                          
                    userDone = false;
                } else {
                    System.out.println("Invalid input, please enter more than 3 letter words."); 
                }
            }
        } while (userDone); //continue until "n"
    }

    private static void getInputAndScramble(Scanner in) {
        System.out.println("Please enter a word to be scrambled"); 
        String word = in.next();                               
        System.out.println(swapLetters(word));
    }

    private static String swapLetters(String word) { 

        /* Convert word into an ArrayList of characters. 
           Create ArrayList size of word, 
           convert String word into a char array and insert every char in                
           the char array into our ArrayList.
        */

        ArrayList<Character> chars = new ArrayList<>(word.length());
        for (char c : word.toCharArray()) {
            chars.add(c);
        }

        //Shuffle, omitting first and last letters
        Collections.shuffle(chars.subList(1, chars.size()-1));

        //Add shuffled letters into an array to output as a word entity
        char[] shuffled = new char[chars.size()];
        for (int i = 0; i < shuffled.length; i++) {
            shuffled[i] = chars.get(i);
        }
        //Return shuffled String
        return new String(shuffled);
    }
}

答案 2 :(得分:1)

关于交换功能,类似的东西应该可以工作:

private static String swapLetters(String word) {
char[] temp = word.toCharArray();
    char swapHelper;
    Random r = new Random();
    int a = r.nextInt(word.length()-2)+1;
    int b = r.nextInt(word.length()-2)+1;
    swapHelper = temp[a];
    temp[a] = temp[b];
    temp[b] = swapHelper;
    word = String.copyValueOf(temp);
    return word;
}

基本上,我将字符串转换为char数组,因此我可以轻松地对其进行操作。 A和B是包含应交换字母索引的变量。之后,将数组转换回字符串并返回。