Kotlin class works not as expected - class

Here's the code in Kotlin.
file1
fun main() {
var player = Player("madrigal")
println(player.name)
printPlayerStatus(player)
println(player.name)
}
private fun printPlayerStatus(player: Player) {
println("${player.name} ")
}
file2
package com.bignerdranch.nyethack
import java.io.File
class Player(
_name: String,
var healthPoints: Int = 100,
var isBlessed: Boolean,
private val isImmortal: Boolean
) {
constructor(name: String) : this(name, isBlessed = true, isImmortal = false) {
if (name.toLowerCase() == "kar") healthPoints = 40
}
var name = _name
get() ="${field.capitalize()} of $hometown"
private set(value) {
field = value.trim()
}
val hometown: String = selectHometown()
init {
require(healthPoints > 0, { "healthPoints must be greater than zero." })
require(name.isNotBlank(), { "Player must have a name" })
}
private fun selectHometown(): String = File("data/towns.txt")
.readText()
.split('\n')
.shuffled()
.last()
fun castFireball(numFireballs: Int = 2) =
println("A glass of Fireball springs into existence. (x$numFireballs)")
fun formatHealthStatus() =
when (healthPoints) {
100 -> "is in excellent condition!"
in 90..99 -> "has a few scratches."
in 75..89 -> if (isBlessed) {
"has some minor wounds, but is healing quite quickly!"
} else {
"has some minor wounds."
}
in 15..74 -> "looks pretty hurt."
else -> "is in awful condition!"
}
fun auraColor(): String {
val auraVisible = isBlessed && healthPoints > 50 || isImmortal
val auraColor = if (auraVisible) "GREEN" else "NONE"
return auraColor
}
}
When I run it I get the results:
Madrigal of Boston
Madrigal of Boston
However, I expect to get the results without the empty string in the middle. Like this:
Madrigal of Boston
Madrigal of Boston
Madrigal of Boston
Then I rewrite the function printPlayerStatus as below :
private fun printPlayerStatus(player: Player) {
println(player.name)
}
Now the output is correct.
Actually I copy the code from the book. And according to the book the code should work fine.
Please, help me to understand why it happens and find my mistake.

Problem is solved. If I avoid working with file and make a simple list of strings, the output gets as expected.

Related

How to print from class with no print lines in class

I am trying to print by making it a string in the class. I am trying not to have any print lines in the class at all. I can't figure out how to not have the print lines in my printBoard method.
class MakeString() {
fun printThis(): String {
var line = arrayOf("hello","printMe")
var addThis = "there"
for (element in array) {
println()
}
return line.toString()
}
override fun toString(): String {
return """
${printThis()}
""".trimIndent()
}
}
You can use a StringBuilder to build the output string:
class Puzzle(var rows :Int,var cols: Int) {
fun printBoard(): String {
var emptyCell = '.'
var board = Array(rows) { Array(cols) { emptyCell } }
val builder = StringBuilder()
for (row in 0 until board.size) {
for (col in 0 until board[row].size) {
builder.append(board[row][col])
}
builder.append('\n')
}
return builder.toString()
}
override fun toString(): String {
return """
${printBoard()}
""".trimIndent()
}
}
fun main () {
var wordss = Puzzle(45, 45)
println(wordss.printBoard())
}

Return templet string from the selected country code

I would like to get the pre-define temple name based on the country selection. Here I'm trying some code, but unable to get that from code. How do I get back messages based on the country code input?
enum Descriptor: String, CaseIterable, CustomStringConvertible {
case fr = "FR"
case jp = "JP"
var description: String {
get {
return self.rawValue
}
}
var mesage : String {
let templet = "Welcome to "
switch self {
case .fr:
return templet + "France"
case .jp:
return templet + "Japan"
}
}
}
extension Descriptor {
static func hasCountry(code: String) -> String? {
return Descriptor.allCases
.map({$0.rawValue})
.first(where: {$0.description == code})
}
}
let x = Descriptor.hasCountry(code: "JP")
print(x)
// Expected output is like
// Welcome to Japan
// or
// Welcome to France
extension Descriptor {
static func hasCountry(code: String) -> String? {
return Descriptor.allCases
.first(where: {$0.description == code})?
.mesage
}
}
You have a tiny bit of mistake in your extension.
So when you do .map({$0.rawValue}), you actually transform all your enum cases to a strings array ["FR", "JP"].
What you actually want to be doing is find your first enum case, and call .mesage on that one.

How I can update my adapter for RecyclerView after change my LiveData?

I created a fragment that in the onActivityCreated method fetches Firebase data by limiting the query to a calendar date. Then I place Observers on my LiveData that are inside my ViewModel and that will deliver the list to my Adapter.
If I add, remove or update items in the same list, the changes are sent to firebase and the adapter reflects them on the screen. It works ok.
But, I am trying to develop a filter button, which will basically change the deadline date for the Firebase query. When I select a particular filter, the viewModel needs to retrieve the data from Firebase limited to the filter date. This generates a new list, having a different size from the previous one.
However, when the query occurs, the Adapter's getItemCount() method stores the size of the last list. This fact confuses the Adapter and the functions notifyItemInserted and notifyItemRemoved end up making confusing animations on the screen after changing the filter. I dont know whats is wrong.
How can I correctly observes LiveData and tell the adapter? Am I making a mistake in the MVVM architecture or forgetting some function?
My Fragment:
class HistoryFragment : Fragment(), OnItemMenuRecyclerViewClickListener {
private lateinit var mSecurityPreferences: SecurityPreferences
private lateinit var viewModel: BalancesViewModel
private lateinit var adapter: BalancesAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setHasOptionsMenu(true)
viewModel = ViewModelProvider(this).get(BalancesViewModel::class.java)
adapter = BalancesAdapter(requireContext())
mSecurityPreferences = SecurityPreferences(requireContext())
return inflater.inflate(R.layout.fragment_history, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setupFilter()
//Setup adapter
adapter.listenerMenu = this
recycler_view_history.adapter = adapter
//Fetch data based in filter by date
viewModel.fetchBalances(mSecurityPreferences.getStoredLong(FILTER_DATE))
// Put logic to listen RealTimeUpdates
viewModel.getRealTimeUpdates(mSecurityPreferences.getStoredLong(FILTER_DATE))
viewModel.balances.observe(viewLifecycleOwner, Observer {
adapter.setBalances(it)
})
viewModel.balance.observe(viewLifecycleOwner, Observer {
adapter.addBalance(it)
})
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.history_menu_filter, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.item_menu_filter_this_month -> {
updateFilter(THIS_MONTH)
}
R.id.item_menu_filter_two_months -> {
updateFilter(TWO_MONTHS)
}
R.id.item_menu_filter_last_six_months -> {
updateFilter(LAST_SIX_MONTHS)
}
R.id.item_menu_filter_all -> {
updateFilter(ALL_MONTHS)
}
}
return super.onOptionsItemSelected(item)
}
private fun setupFilter() {
var filterOption = mSecurityPreferences.getStoredLong(FILTER_DATE)
if (filterOption == 0L){
filterOption = HandleDate.getLongToFilter(LAST_SIX_MONTHS)
mSecurityPreferences.storeLong(FILTER_DATE, filterOption)
}
}
private fun updateFilter(filterOption: Int){
val newFilterOption = HandleDate.getLongToFilter(filterOption)
mSecurityPreferences.storeLong(FILTER_DATE, newFilterOption)
updateUI()
}
private fun updateUI(){
viewModel.fetchBalances(mSecurityPreferences.getStoredLong(FILTER_DATE))
viewModel.getRealTimeUpdates(mSecurityPreferences.getStoredLong(FILTER_DATE))
}
}
My ViewModel:
class BalancesViewModel : ViewModel() {
private val userReference = FirebaseAuth.getInstance().currentUser!!.uid
private val dbUserReference = FirebaseDatabase.getInstance().getReference(userReference)
private val _balances = MutableLiveData<List<Balance>>()
val balances: LiveData<List<Balance>>
get() = _balances
private val _balance = MutableLiveData<Balance>()
val balance: LiveData<Balance>
get() = _balance
private val _result = MutableLiveData<Exception?>()
val result: LiveData<Exception?>
get() = _result
fun addBalance(balance: Balance) {
balance.id = dbUserReference.push().key
dbUserReference.child(NODE_BALANCES).child(balance.id!!).setValue(balance)
.addOnCompleteListener {
if (it.isSuccessful) {
_result.value = null
} else {
_result.value = it.exception
}
}
}
private val childEventListener = object : ChildEventListener {
override fun onCancelled(error: DatabaseError) {
}
override fun onChildMoved(snapshot: DataSnapshot, p1: String?) {
}
override fun onChildChanged(snapshot: DataSnapshot, p1: String?) {
val balance = snapshot.getValue(Balance::class.java)
balance?.id = snapshot.key
_balance.value = balance
}
override fun onChildAdded(snapshot: DataSnapshot, p1: String?) {
val balance = snapshot.getValue(Balance::class.java)
balance?.id = snapshot.key
_balance.value = balance
}
override fun onChildRemoved(snapshot: DataSnapshot) {
val balance = snapshot.getValue(Balance::class.java)
balance?.id = snapshot.key
balance?.isDeleted = true
_balance.value = balance
}
}
fun getRealTimeUpdates(longLimitDate: Long) {
dbUserReference.child(NODE_BALANCES).orderByChild(COLUMN_DATE_MILLI)
.startAt(longLimitDate.toDouble()).addChildEventListener(childEventListener)
}
fun fetchBalances(longLimitDate: Long) {
dbUserReference.child(NODE_BALANCES).orderByChild(COLUMN_DATE_MILLI)
.startAt(longLimitDate.toDouble())
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(error: DatabaseError) {}
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val listBalances = mutableListOf<Balance>()
for (balanceSnapshot in (snapshot.children)) {
val balance = balanceSnapshot.getValue(Balance::class.java)
balance?.id = balanceSnapshot.key
balance?.let { listBalances.add(it) }
}
listBalances.sortByDescending { it.dateMilli }
_balances.value = listBalances
}
}
})
}
fun updateBalance(balance: Balance) {
dbUserReference.child(NODE_BALANCES).child(balance.id!!).setValue(balance)
.addOnCompleteListener {
if (it.isSuccessful) {
_result.value = null
} else {
_result.value = it.exception
}
}
}
fun deleteBalance(balance: Balance) {
dbUserReference.child(NODE_BALANCES).child(balance.id!!).setValue(null)
.addOnCompleteListener {
if (it.isSuccessful) {
_result.value = null
} else {
_result.value = it.exception
}
}
}
My Adapter:
class BalancesAdapter(private val context: Context) :
RecyclerView.Adapter<BalancesAdapter.BalanceViewModel>() {
private var balances = mutableListOf<Balance>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
BalanceViewModel(
LayoutInflater.from(parent.context)
.inflate(R.layout.item_recyclerview_balance, parent, false)
)
override fun getItemCount() = balances.size
override fun onBindViewHolder(holder: BalanceViewModel, position: Int) {
holder.view.text_view_value_balance_item.text = balances[position].value
holder.view.text_view_date_item.text = balances[position].date
}
fun setBalances(balances: List<Balance>) {
this.balances = balances as MutableList<Balance>
notifyDataSetChanged()
}
fun addBalance(balance: Balance) {
val index = balances.indexOf(balance)
if (!balances.contains(balance)) {
balances.add(balance)
notifyItemInserted(index)
} else {
if (balance.isDeleted) {
balances.removeAt(index)
notifyItemRemoved(index)
} else {
balances[index] = balance
}
}
notifyItemRangeChanged(index, itemCount)
}
class BalanceViewModel(val view: View) : RecyclerView.ViewHolder(view)
}
Tnks for your attention.
Okay, it's been 4 days since I asked this question and after feeling a little frustrated with the project I come back here on StackOverFlow to post my own answer.
The problematic issue within the code I showed is in my Adapter's addBalance method.
When I created the Balance data model, I set the isDeleted attribute to identify that it was deleted. Upon entering Firebase it receives a NULL value and therefore it ceases to exist.
Then, as I have two listeners (one defined in the addListenerForSingleValueEvent method and the other defined in the addChildEventListener method), one ends up triggering the other when there is a change in the Firebase data, but I don't want to go into detail on that issue. The fact is that I checked that my addBalance method was being called after I deleted an object, causing that object to be inserted back into the Adapter's data list, even before the removal operation ended in Firebase.
So I changed the logic of my method to make sure that my object was deleted and only included it in my Adapter list after checking the isDeleted attribute.
fun dealWithBalance(balance: Balance){
val index = balances.indexOf(balance)
if(balance.isDeleted && balances.contains(balance)){
balances.removeAt(index)
notifyItemRemoved(index)
} else if(!balance.isDeleted && !balances.contains(balance)){
balances.add(balance)
} else if(index >= 0){
balances[index] = balance
notifyItemChanged(index)
}
}
I renamed addBalance to dealWithBalance...

Conditional return from method in scala

I am a java developer and an trying to conditionally return from a method in scala.
def parseDates: Boolean = {
var date = aoc4Xml \\ "FinancialStmtFromDate" text
if (StringUtils.isEmpty(date)) {
addErrorStringFromString("Please enter the financial year start date")
return false
}
aoc4Dto.finYearStartDate = DateUtils.getDateFromFormatOfString(date)
date = aoc4Xml \\ "FinancialStmtToDate" text
if (StringUtils.isEmpty(date)) {
addErrorStringFromString("Please enter the financial year end date")
return false
}
aoc4Dto.finYearEndDate = DateUtils.getDateFromFormatOfString(date)
true
}
This does not compile, at the first if block saying illegal start of expression. How do I implement the above where returning early from a method was considered the best way to handle things.
Just to clarify things:
The above problem technically reduces to
def test(testString:String) = {
if(testString == "Chennai"){
println("correct")
return true
}
println("outside if")
false
}
test("Chennai")
The above will not compile at line return true. There is no problem with the first xml xpath and text.. please ignore all of it and check the conditional return from the method.
Next time please submit codes without the need to stubb a lot of functionality. The stabbed snipeet, that compiles:
object StringUtils{
def isEmpty(s: String) = true
}
object aoc4Xml{
def \\(s: String) = {
new {def text = "test"}
}
}
object DateUtils{
def getDateFromFormatOfString(s: String) = 0
}
object Main {
val date = "date"
def addErrorStringFromString(s: String) = println(s)
object aoc4Dto{
var finYearStartDate = 0
var finYearEndDate = 0
}
def parseDates: Boolean = {
var date = (aoc4Xml \\ "FinancialStmtFromDate" text)
if (StringUtils.isEmpty(date)) {
addErrorStringFromString("Please enter the financial year start date")
return false
}
aoc4Dto.finYearStartDate = DateUtils.getDateFromFormatOfString(date)
date = (aoc4Xml \\ "FinancialStmtToDate" text)
if (StringUtils.isEmpty(date)) {
addErrorStringFromString("Please enter the financial year end date")
return false
}
aoc4Dto.finYearEndDate = DateUtils.getDateFromFormatOfString(date)
true
}
}
The difference(just enclose with bracers):
var date = (aoc4Xml \\ "FinancialStmtFromDate" text)
date = (aoc4Xml \\ "FinancialStmtToDate" text)
And your second snippet has another error:
def test(testString:String): Boolean = {
if(testString == "Chennai"){
println("correct")
return true
}
println("outside if")
false
}
just provide returning type:
def test(testString:String): Boolean = {

Content filter function not working... Can't find bug

I've been messing with a content filter system in XCode 6 Playground in Swift and the idea is that if I input a string with multiple words (Ex: "Apple Oranges Bananas"), the function will separate this string into an array then cycle through the database with any of these words and should return true if there is a match. So my function returns true if I put a whole word but returns false when I put a single letter... I used the "RangeOfString" line so it should go through the word character by character but i don't know.. Really stumped.
Here is the code..
// Playground - noun: a place where people can play
import UIKit
class Person {
var name = ""
var age = 0
init(name: String, age:Int) {
self.name = name
self.age = age
}
}
var filteredItems = [Person]()
var items = [ Person(name: "Anders", age: 23), Person(name: "Alice", age: 56), Person(name: "Amanda", age: 88)]
items.append(Person(name: "Andrew", age: 23))
func filterContentForSearchText(searchText : String) -> Bool
{
var filtered = false
//Filter the array using the filter method
filteredItems = items.filter({( search : Person) -> Bool in
let stringMatch = queryValidator(searchText, search.name)
let intMatch = queryValidator(searchText, String(search.age))
filtered = (stringMatch != false || intMatch != false)
return (stringMatch != false || intMatch != false)
})
return filtered
}
func queryValidator(search : String, database : String) -> Bool
{
//Function that splits search query into multiple querys
let query = search.uppercaseString.componentsSeparatedByString(" ")
var queryFound = false
for(var i = 0; i < query.count; i++)
{
let match = query[i].uppercaseString.rangeOfString(database.uppercaseString)
if(match != nil)
{
queryFound = true
}
}
return queryFound
}
filterContentForSearchText("a")
Any help would be really appreciated!!
string.rangeOfString does not do a prefix match. So if you search with "a", you don't have any people in your array with a name that is "a". If you want to do prefix match, try using String.hasPrefix (as described in https://developer.apple.com/library/mac/Documentation/General/Reference/SwiftStandardLibraryReference/index.html).