[英]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:几点:
equals()
between a String and a char (' ' are for chars, " " are for Strings).equals()
(' ' 代表字符,“ " 代表字符串)。 Simple fix - just put your 'y' into "y", same for 'n'.getInputAndScramble
.getInputAndScramble
。 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
.您假设两个随机数
a
和b
具有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()
、将String
与char
进行比较、使用错误的换行符、不剥离换行符等。 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.