我正在嘗試撰寫一個代碼來列印用戶在控制臺中輸入的任何內容,但是當我插入一個使用 readLine() 函式作為其條件的 while 回圈時,即使用戶輸入,該代碼也將始終不回傳任何內容在控制臺中輸入了一些東西。代碼如下:
fun main() {
while(readLine()=="A") print("A is inputted")
print(readLine() " 123")
}
我的意圖是當用戶輸入(到第一個readLine())除“A”之外的任何內容時,代碼將繼續到下一行,然后列印出輸入的下一個字串(到第二個readLine())與“123”連接。
例如:“asdfasdfaf 123”,但實際上它只會列印“123”
誰能告訴我為什么會這樣?獲得預期行為的代碼是什么?任何幫助將不勝感激,因為我是新手,謝謝:)
編輯:
發布后一段時間我找到了解決方案,這有點奇怪。
fun main(args: Array<String>) {
while(readln()=="A") print("A is inputted")
readLine() // throwaway readLine()
print("${readLine()} 123")
}
我可能是錯的,但從我在這里收集的資訊來看,在 while 回圈停止后,代碼以某種方式輸入了任何內容——我認為這是一個空值——進入第二個readLine(). readLine()所以我只是在這兩者之間放了一個扔掉。我仍然不知道為什么會這樣
uj5u.com熱心網友回復:
通過使用readLine()兩次,您實際上是在要求 2 條輸入。這是您的代碼當前正在執行的操作:
- 您正在讀取輸入(使用
while回圈?您的意思是使用if陳述句代替嗎?) - 您正在讀取第二個輸入,并將“123”附加到第二個輸入。
試試這個:
fun main() {
//Some kind of for or while loop if you want to constantly take input
val input = readLine()
if (input == "A") {
println("A has been input")
println("$input 123")
}
}
uj5u.com熱心網友回復:
它的撰寫方式,你必須輸入你的“其他”輸入兩次- 一次所以它被視為不是“A”,當你嘗試列印它時再次 -readLine()當你輸入不是“A”的東西時你打了兩個電話
猜測一下,你得到了," 123"因為你輸入"asdfasdfaf"了退出 while 回圈,但是你點擊了第二個readLine(),你可能只是再次點擊 Return,想知道為什么它沒有列印出來。所以 print 陳述句讀入你剛剛輸入的空行,你得到" 123"
如果您想訪問非“A”輸入,則需要存盤它 - 這樣您就可以在您的if條件下檢查它,并print稍后在您的陳述句中使用它。這是您可以做到的一種方法
fun main() {
// do-while runs the loop -at least once- and checks the repeat condition at the end
do {
val input = readLine()
if (input == "A") print("A is inputted")
// this prints inside the loop, now we just need to exit it
else print("$input 123")
} while (input == "A") // stops looping the first time you get non-"A" input
}
這就是 Cloudate9 的目的
uj5u.com熱心網友回復:
我不確定您要做什么,但是我閱讀和理解您的帖子的方式,這就是我想出的:
fun main() {
val input = readLine()
if (input == "A") {
println("A has been inputted")
} else {
println("$input 123")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/479633.html
標籤:科特林
下一篇:問題在Recyclerview上使用LiveData、Retrofit、Coroutine實作更新UI:配接器Recyclerview未更新
