简体   繁体   English

Java - 单词加扰器[保留第一个和最后一个字母]

[英]Java - word scrambler [keeping first and last letter]

My assignment is to write a program to scramble a word while maintaining the same first and last letter and only swapping two letters, then prompt the user to continue if they wish.我的任务是编写一个程序来打乱一个单词,同时保持相同的第一个和最后一个字母,只交换两个字母,然后提示用户继续。

Example: userInput = bacon |示例: userInput = bacon | Output = bcaon

I've attached an imagine of my program, there may be several issues, but as it stands I can't really run it due to the errors in the image.我附上了我的程序的想象,可能有几个问题,但由于图像中的错误,我无法真正运行它。 I'm really confused because I got a TA to help me on this assignment, and they seemed to think this would definitely work, but as you can see it does not.我真的很困惑,因为我有一个助教来帮助我完成这项任务,他们似乎认为这肯定会奏效,但正如你所看到的那样。

I would really appreciate if someone could tell me what exactly is wrong and why.如果有人能告诉我到底出了什么问题以及原因,我将不胜感激。 And if you have anything to add to make this program work, I'd really, really appreciate that too, but bottom line is I just want to understand what's wrong and why.如果您要添加任何内容以使该程序正常运行,我也非常非常感激,但最重要的是我只是想了解什么是错的以及为什么。

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;
}

Several points:几点:

  1. Why not use something already done exactly for what you are trying to do - Collections.shuffle ?为什么不使用已经完成的事情来完成您正在尝试做的事情 - Collections.shuffle See comments in the code for understanding how it works.请参阅代码中的注释以了解其工作原理。
  2. You can't use equals() between a String and a char (' ' are for chars, " " are for Strings).您不能在 String 和 char 之间使用equals() (' ' 代表字符,“ " 代表字符串)。 Simple fix - just put your 'y' into "y", same for 'n'.简单的修复 - 只需将“y”放入“y”中,“n”也是如此。
  3. I've refactored the code at the beginning that we used to get user input and then scramble into a separate method, so we can reuse it again - getInputAndScramble .我在开始时重构了我们用来获取用户输入然后加扰到一个单独的方法中的代码,因此我们可以再次重用它 - getInputAndScramble
  4. And finally, I've used a do-while loop to keep looping until the user stops the loop with the "n" letter.最后,我使用了一个 do-while 循环来保持循环,直到用户用“n”字母停止循环。

Please see my comments in the code, hopefully will clear things up.请查看我在代码中的注释,希望能解决问题。

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);
    }
}

You are assuming that the two random number a and b have the property that a < b .您假设两个随机数ab具有a < b的属性。 What if a >= b ?如果a >= b呢? Then word.substring(a+1, b) will throw an error .然后word.substring(a+1, b)会抛出错误

To fix it, just make sure that a < b is maintained (regenerating, swapping, etc.).要修复它,只需确保维护a < b (重新生成、交换等)。

But to be sure, there are more than just this bug in your code.但可以肯定的是,您的代码中不仅仅是这个错误。 For example, using next() , comparing String with char , using wrong newline character, not striping newline character, and so on.例如,使用next() 、将Stringchar进行比较、使用错误的换行符、不剥离换行符等。 You might want to add some print statements in your code you see what is actually happening.您可能希望在代码中添加一些打印语句,以查看实际发生的情况。

Well, as for the swapping function, something like that should work:好吧,至于交换功能,这样的事情应该可以工作:

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;
}

Basically, im converting string to char array so i can operate on them with ease.基本上,我将字符串转换为字符数组,这样我就可以轻松地对它们进行操作。 A and B are variables that contain index of letters that should be swapped. A 和 B 是包含应该交换的字母索引的变量。 After that, array is converted back to string and returned.之后,数组被转换回字符串并返回。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中制作单词加扰器 - Making a word scrambler in java 在Java上替换单词中的第一个,中间和最后一个字母 - Replacing first, middle and last letter in a word on Java Java函数类似于文字游戏,最后一个字母=下一个单词的第一个字母 - Java Function similar to word game, last letter = first letter of next word 如何将第一个字母大写并小写 rest,同时在完全大写的情况下保持单词大写 - java - How to capitalize first letter and lowercase the rest while keeping the word capital if it is in fully uppercase - java Java-取单词的第一个字母并替换为另一个单词的第一个字母 - Java - take first letter of word and replace with first letter of another word 第一个字母与最后一个字母,第二个字母与倒数第二个字母之间的差之和,依此类推,直到单词的中心 - Sum of the Difference between the first letter and the last letter, second letter and the penultimate letter, and so on till the center of the word 在Java中将单词的首字母更改为大写 - Change the first letter of a word to uppercase in java 在Java中切换字符串的第一个和最后一个字母? - Switching the first and last letter of a string in Java? 在Java中交换字符串的第一个和最后一个字母? - Swapping the first and the last letter of a string in Java? 将字母&#39;a&#39;的第一个外观与最后出现的字母&#39;o&#39;Java交换位置 - Swap positions of the first appearance of letter 'a' with the last appearance of letter 'o' Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM