我正在尝试创建一个程序,该程序接受用户的输入,然后将用户的输入扫描到带有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
答案 0 :(得分:1)
你在这里有一些时髦的逻辑。一些事情:
userInput = keyboard.nextLine(); //stores user input
int userInputLength = userInput.length(); //to find word count
userInputLength
是userInput
字符串的长度,它是字符串中的字符数,而不是字数。
看起来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