我是essentiel試圖創造一個電影猜謎遊戲,有點像hang子手,但你需要猜測一個電影標題。電影標題使用下劃線('_')字符表示每個字符進行編碼。當用戶輸入正確的字母時,相應字母位置的下劃線將變爲該字母。用戶使用掃描儀將他的猜測作爲單個字符輸入。 我的問題是,一些電影標題包含空格('')。但我無法使用掃描程序來返回空格...我的猜測是掃描程序使用空白作爲默認分隔符,因此它不會將空格作爲字符返回,因爲它使用空格將輸入分爲標記?帶掃描器的打印空間
'return a space'我的意思是考慮一個空間作爲輸入,而不是作爲分隔符。
任何人都可以給我一個解決方案,我怎麼可以從用戶輸入檢測空間?
此代碼應該通過movieTitle讀取,然後如果電影標題在索引i處包含空格,並且用戶輸入是空格,則codedMovieTitle應該在位置i處更新一個空格,而不是下劃線。但是這不起作用。當我輸入使用的掃描儀沒有任何反應
for (int i = 0; i < movieTitle.length(); i++) {
if(Character.isSpaceChar(movieTitle.charAt(i)) &&
Character.isSpace(userInput)){
encodedMovieTitle = encodedMovieTitle.substring(0, i)
+ userInput
+ encodedMovieTitle.substring(i + 1);
}
}
的空間......這是我的掃描儀代碼:
Scanner scanner = new Scanner(System.in);
char userInput;
while(!gameIsWon && (numberOfGuessesLeft != 0)) {
while (scanner.hasNextInt()) {
System.out.println("You must enter a single character, try again.");
scanner.next();
}
userInput = scanner.nextLine().charAt(0);
我也有我的使掃描儀輸入是非大小寫敏感的掙扎。一些電影中有大寫字母。 如果標題爲「暴風雪」,並且用戶輸入了字符's',則生成的編碼電影標題將爲「_ _ _ _ _ _ _ _」,而不是「S _ _ _ _ _ _ _」
如果有人有一個很好的解決方案!我發現大多數解決方案涉及到使用字符串,但我使用字符作爲我的userInput等,因此我想知道是否有涉及字符的解決方案。
代碼檢查是userInput(字符)是在movieTitle(字符串):
for (int i = 0; i < movieTitle.length(); i++) {
if (updatedCodedMovieTitle.charAt(i) != userInput && movieTitle.charAt(i) == userInput) {
updatedCodedMovieTitle = updatedCodedMovieTitle.substring(0, i)
+ userInput
+ updatedCodedMovieTitle.substring(i + 1);
wordHasBeenUpdated = true;
}
if(Character.isSpaceChar(movieTitle.charAt(i)) && Character.isSpaceChar(userInput)){
updatedCodedMovieTitle = updatedCodedMovieTitle.substring(0, i)
+ " "
+ updatedCodedMovieTitle.substring(i + 1);
}
}
你能否也粘貼掃描儀代碼? –
你能告訴我們你如何創建掃描儀? –
我更新了我的評論,以添加掃描儀代碼 – CheckCho