java - 使用用户字符串中的反向单词创建数组
问题描述
我正在创建一个程序,用户在其中输入一串单词(例如:我爱你),程序返回字符串中的单词数组(例如:I evol ouy)。但是,我无法让我的代码正确编译,并尝试调试,但看不到问题出在哪里。
我试图在 Slack 上寻找类似的问题,但发现的问题与从字符串中重新排列单词有关(例如:你我爱),我找不到与我类似的问题,涉及将字符串转换为数组和然后操作数组。
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
char[] entryToChar = userEntry.toCharArray();
System.out.println(Arrays.toString(entryToChar));
String[] splitInput = userEntry.split(" ");
String reverseWord = "";
int temp;
String[] reverseString = new String[splitInput.length];
for (int i = 0; i < splitInput.length; i++)
{
String word = splitInput[i];
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
for (int k = 0; k < splitInput.length; k++) {
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
}
} System.out.println("Your sttring with words spelled backwards is " + reverseWord[j]);
我正在避免使用“StringBuilder”方法,因为我还没有研究过它,并尝试查看是否可以使用交换来获取新字符串,如下面的代码所示:
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
解决方案
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word, reverseWord;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
用户输入:我爱你
String[] splitInput = userEntry.split(" ");
splitInput:[我,爱,你]
for (int i = 0; i < splitInput.length; i++)
{
word = splitInput[i];
reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
splitInput[i] = reverseWord;
}
splitInput: [I, evol, uoy]
System.out.println("Your string with words spelled backwards is: " + String.join(" ", splitInput));
}
}
你的单词倒着写的字符串是:I evol uoy
推荐阅读
- python - raise KeyError(key) KeyError: 'formatters'
- python-3.x - 语法错误?如何解决这个问题,它甚至在修复后运行吗?
- html - How to change input label value programmaly using Angular
- java - Runtime permission was granted but still getting the error java.io.FileNotFoundException: /storage/emulated/0/... .jpg (Permission denied)
- excel - How to set number format on multiple columns?
- robotframework - 如何使用 RobotFramework 为 SikuliLibrary 应用 if else 条件?
- ios - ARKit:在跟踪图像之外添加虚拟 2D 图像
- docker - docker 中 nginx 后面的 Keycloak 导致 404 和不定式重定向
- elasticsearch - 如何使用 Postman 和 ElasticSearch 向请求正文添加过滤器?
- ios - 无法使用 safari 打开某些网站