gpt4 book ai didi

java - 如何获取用户输入,将其添加到新扫描仪,然后将输入扫描到数组中?

转载 作者:行者123 更新时间:2023-12-02 13:37:21 24 4
gpt4 key购买 nike

我正在尝试创建一个程序,该程序接受用户的输入,然后使用 for 循环将用户的输入扫描到数组中。这样我就可以循环遍历数组来查找字符串是否是回文单词。单词回文与回文的不同之处在于它是整个单词的反向而不是每个单独的字母的反向。当我编写的程序打印时,它只打印 null,我认为这意味着它没有存储扫描仪扫描的内容。以下是我写的:

String userInput, scannedWord;
Scanner keyboard = new Scanner(System.in); //scanner for user input

System.out.print("Please enter a sentence: ");
userInput = keyboard.nextLine(); //stores user input

Scanner stringScan = new Scanner(userInput); //scanner to scan through user input

int userInputLength = userInput.length(); //to find word count
int wordCount = 0; //for array size


for (int i = 0; i < userInputLength; i++) //finds word count
{
while(stringScan.hasNext())
{
scannedWord = stringScan.next();
wordCount = wordCount + 1;
}
}

String stringArray[] = new String[wordCount];

for (int i = 0; i < userInputLength; i++) //should store scanned words into the array
{
while (stringScan.hasNext())
{
scannedWord = stringScan.next();
stringArray[i] = scannedWord;
}
}

System.out.println(Arrays.toString(stringArray)); //how I've checked if it's storing

最佳答案

这里有一些奇怪的逻辑。一些事情:

userInput = keyboard.nextLine(); //stores user input
int userInputLength = userInput.length(); //to find word count

userInputLengthuserInput 字符串的长度,它是字符串中的字符数,而不是单词数。

看起来while循环只是用来计算所需的数组大小,但外部的for循环不是必需的。您实际上是在说,对于输入字符串中的每个字符,虽然扫描仪有另一个单词,但计算该单词的数量,这没有多大意义。

您在第二个 for 循环中执行了类似的操作,但这也没有多大意义。

for (int i = 0; i < userInputLength; i++) //finds word count
{
while(stringScan.hasNext())
{
scannedWord = stringScan.next();
wordCount = wordCount + 1;
}
}

使用List会更容易,并且可以省去固定大小数组带来的麻烦。您只需初始化列表并向其中添加内容即可,而不必关心它有多大。

List<String> words = new ArrayList<String>();
words.add(word1);
words.add(word2);

这里有一些代码可以稍微简化您的问题:

Scanner keyboard = new Scanner(System.in); //scanner for user input

System.out.print("Please enter a sentence: ");

String userInput = keyboard.nextLine(); //stores user input

Scanner stringScan = new Scanner(userInput); //scanner to scan through user input

List<String> words = new ArrayList<String>();

while (stringScan.hasNext())
{
String scannedWord = stringScan.next();
words.add(scannedWord);
}

System.out.print(Arrays.toString(words.toArray())); // nasty! but you can see what's in the array for debugging

关于java - 如何获取用户输入,将其添加到新扫描仪,然后将输入扫描到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42916042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com