我試圖創建一個程序,它接受用戶的輸入,然後用for循環掃描用戶輸入到數組中。這樣我可以遍歷數組來查找該字符串是否是一個單詞迴文。單詞迴文不同於迴文,因爲它是整個單詞的反向,而不是每個單獨的字母。當我編寫的程序打印時,它只是打印出空白,我相信這意味着它不存儲掃描儀掃描的內容。 下面是我寫的東西:如何獲取用戶輸入,將其添加到新掃描儀,然後將輸入掃描到數組中?
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
你的描述很模糊。所以你想要做的是,一個字符串是否是一個迴文。 –
'stringScan'在第一次循環的第一次迭代結束時用完。目前還不清楚爲什麼你甚至有嵌套循環。 – shmosel