Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Maybe I'm too tired, but when adding the following Log.d in the code (now commented out) the , Studio shows a compile error on the last "else if" (where (formId == 98))... Please advise
formViewModel?.questionGeneralData?.id?.let { formId ->
if (formId == 10 && !interactor.getIsRetroactive()) {
interactor.setCaffeineCounter(answer.toString())
// Log.d("5732", "455ryhrdhgbfhbdrfhbg")
} else if (formId == 14) {
if (answer == 0) {
if (BuildConfig.FLAVOR == BOOST_FLAVOR) {
interactor.addSkippedForm(15, FormEnums.FormType.MORNING_FORM)
} else {
interactor.addSkippedForm(15, FormEnums.FormType.MORNING_FORM_REFRESH)
}
} else {
interactor.removeSkippedForm(15)
}
} else if (formId == 97 && !interactor.getIsRetroactive()) {
HomeSharedPrefs.put(SleepApp.getInstance().applicationContext, caffeineTaken, answer)
} else if (formId == 98 && !interactor.getIsRetroactive()) {
HomeSharedPrefs.put(SleepApp.getInstance().applicationContext, alcoholTaken, answer)
}
}
I would say that when you do that, the return type of that first if statement is different than all the other statements. Since the let function (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/let.html) expects a type for the return value that might be causing this compilation issue.
Use .also instead OR return same data-type from all if-else branches.
Also, put that log statement above interactor.setCaffeineCounter(answer.toString()).
Based on Joao Dias answer, the solution is to switch places the Log.d with the line before it (put it after the Log.d), so first the Log is executed, and then the line after it runs, and returns the value, that the let expects
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 29 days ago.
Improve this question
public Person getOldest(Person personA, Person personB, Person personC) {
A method passes in 3 parameters of object Person in which Person can use the getAge() method. I'm trying to find the oldest person but some of them may be null in which case will return the oldest person that isn't null. If all three are null then it will return null.
I thought of using a bunch of nested if, else if loops to go through every combination of null and getAge() to find the oldest Person but there has to be a better method.
You can make another method called getOldest(p1, p2) with only 2 parameters and then do the following:
Person getOldest(p1, p2) {
if (p1 == null && p2 == null) { return null; }
if (p1 == null) { return p2; }
if (p2 == null) { return p1; }
if ( p1.getAge() > p2.getAge() ) { return p1; } else { return p2; }
}
Person getOldest(p1, p2, p3) { return getOldest(p1, getOldest(p2, p3)); }
Sorry for the formatting, I'm on a phone.
This question already has answers here:
Swift 'if let' statement equivalent in Kotlin
(16 answers)
Closed 4 years ago.
let say I have this variable
val number : Int? = 12
I want to make control flow based on the variable, if the variable is null then do something, otherwise do something else
in Swift I can make something like this:
if let number = number {
print(number)
} else {
// do something else
}
I actually can do like this
if number != null {
print(number!!) // I want to avoid exclamation mark like this
} else {
// do something else
}
but I want to avoid exclamation mark, like in print(number!!)
I previously though that I can do something like this
number?.let {
print(it)
} else {
// else block is not available in let in Kotlin
}
so how to solve this ?
The ?. means it will be executed only if the left side is not null.
The ?: operator executes the right side only if the left side is not null.
You may have something like:
theExpression().toCompute().theNumber?.let { number ->
print("This is my number $number
} ?: run {
print("There is no number")
}
Here we use T.let extension function for the then clause and run{ } (extension) function for the else clause.
Warning: The semantics is that you expected to return non-null value from the let {...} closure to avoid the `run {..} closure from being executed. Thus the code like:
number?.let { null } ?: run { 42 } === 42 (and not null)
A couple of days ago I had an interview for an internship and I've been asked to write a function that tests if another function (which was adding 2 numbers together) is working. My answer was something similar to this:
bool addTest(double a, double b){
if((a+b) == addFunction(a, b))
return true;
else
return false;
}
However, they did not seem impressed with my answer. How else could I do it?
Test cases should be written with parameters and expected answers hard coded into them to eliminate any uncertainty.
bool addTest(){
//2+2=4
if (addfunction(2,2) !=4){
return false;
}
//1.66666+7.9=9.56666
if (addFunction(1.66666, 7.9) != 9.56666){
return false;
}
//0+0=0
if (addFunction(0,0) != 0){
return false;
}
//all tests passed
return true;
}
If a bug is found later on in the development, the conditions that caused the bug should be added to the test function. For example, one day you try to add two negative numbers, only to find they return a positive number. Adding a test case for this will ensure this bug is caught again if the function changes in the future.
//addFunction(-8, -1) //Oops! We return positive 9! Let's fix the bug and make a new test
//-8 + -1 = -9
if (addFunction(-8, -1) != -9){
return false;
}
It also wouldn't hurt to add test cases that verify two values don't produce a wrong answer, though this is harder to cover all test cases.
//-8 + -1 = -9
if (addFunction(-8, -1) == 9){
return false;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I'm getting Expected expression errors on the following code:
(void) for(t; t < kPlatformsStartTag + kNumPlatforms; t++) { //error here
CCSprite *platform = (CCSprite*)[batchNode getChildByTag:t];
CGSize platform_size = platform.contentSize;
CGPoint platform_pos = platform.position;
max_x = platform_pos.x - platform_size.width/2 - 10;
min_x = platform_pos.x + platform_size.width/2 + 10;
float min_y = platform_pos.y + (platform_size.height+bird_size.height)/2 - kPlatformTopPadding;
if(bird_pos.x > max_x &&
bird_pos.x < min_x &&
bird_pos.y > platform_pos.y &&
bird_pos.y < min_y) {
[self jump];
}
}
(void) for(t; t < kCloudsStartTag + kNumClouds; t++) { //error here
CCSprite *cloud = (CCSprite*)[batchNode getChildByTag:t];
CGPoint pos = cloud.position;
pos.y -= delta * cloud.scaleY * 0.8f;
if(pos.y < -cloud.contentSize.height/2) {
currentCloudTag = t;
[self resetCloud];
} else {
cloud.position = pos;
}
}
The error is found where the "for" code is. I put the (void) code in because I will get an Expression result unused error. Any ideas?
The (void) before the for loop does not make sense.
You have to remove the (void) before the for loop because it's not a valid c syntax. You can't solve an error with another error.
You may ask the question : Why puting (void) before the for loop prevented the unused expression error. Well that's because the debugger didn't reach it. and it doesn't know for what is for as he expected a resulted value from it to cast it to void.
When the compiler is generating the error: Unused Entity Issue - Expression result unused. That's means that your program is evaluating an expression without using it.
In your case at the for loop if the t variable is already initialized as you want it, you shouldn't put it at the first part as it will be considired as an unused expression.
for(; t < kPlatformsStartTag + kNumPlatforms; t++) { // keep the first expresion empty
// ...
}
You've already got answers about the bogus (void), but not about the unused expression.
for(t; t < kCloudsStartTag + kNumClouds; t++)
The initial expression here, t, has absolutely no effect, and for that reason has no business being present at all. The value of t is read and immediately discarded, and any decent compiler will optimise that by not even bothering to read t. You do not need an expression here. You can remove it, and write
for(; t < kCloudsStartTag + kNumClouds; t++)
although personally, I might be tempted to go with a while loop instead.
Edit: reading your code more closely, your code seems to need to give t an initial value.
for(t = 0; t < kCloudsStartTag + kNumClouds; t++)
Either way, your attempt to suppress the warning without understanding what the warning was telling you wasn't a good idea.
I am developing an app where the user receives an overall score and are judged from that score and given a title. However, with the code I am using, the end result is always the same, no matter what score the subject gets. I dont know if this a math problem or a code problem, as it always comes up with the first option: You have no SWAG whatsoever...
if (totalScore<24) {
describe.text = #"You have no SWAG whatsoever...";
}
else if (25<totalScore<49) {
describe.text = #"You seem to be new to SWAG.";
}
else if (50<totalScore<74) {
describe.text = #"You have a bit of SWAG, not enough though.";
}
else if (75<totalScore<99) {
describe.text = #"You definately have SWAG!";
}
else if (totalScore == 100) {
describe.text = #"You are a GOD of SWAG.";
}
else if (25<totalScore<49) {
should be:
else if (25<totalScore && totalScore<49) {
The way you wrote it is parsed as if you'd written:
else if ((25<totalScore) < 49) {
25<totalScore will be either 1 or 0 depending on whether it's true or false. Either way, it's less than 49.
Also, all your comparisons should be <= rather than <. Otherwise, you're excluding all the boundary values.
building if in this way
if (25<totalScore<49) {...}
is risky.In reality you do something like
25<totalScore -> YES/NO (values will be casted from BOOL to int as 1/0)
and then you will do
0/1 < 49 which will be always true.
so in total your if is wrong.
Your first line of code looks right from what you have displayed so far? You need to output what total score is. You are maybe not setting it before running your code?
Failing that, are you sure its compiling properly? You need to use && in your subsequent if statements.
Also, you need to use <=, because at the moment, if the score is 24 it wont work.