Clarification on ending a while loop [closed] - while-loop

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am currently working with a while loop and was confused as to why I couldn't end the loop.
I played around with it for a little while and for some reason the following code works and ends the while loop:
boolean keepGoing = true;
while (keepGoing != false)
{
//execute code
}
System.out.println("Would you like to continue? Enter Y for yes or N for no.");
String keepGoingYesOrNo = input.nextLine();
if (keepGoingYesOrNo.equals("Y"))
{
keepGoing = true;
matchCount=0;
guessCount=0;
}
else
{
System.out.println("Goodbye!");
keepGoing = false;
But the alternative doesn't end the while loop:
boolean keepGoing = true;
while (keepGoing = true)
{
//execute code
}
System.out.println("Would you like to continue? Enter Y for yes or N for no.");
String keepGoingYesOrNo = input.nextLine();
if (keepGoingYesOrNo.equals("Y"))
{
keepGoing = true;
matchCount=0;
guessCount=0;
}
else
{
System.out.println("Goodbye!");
keepGoing = false;
Shouldn't while (keepGoing = true) and while (keepGoing != false) be the same thing. I got the code to work but I was hoping to get some clarification on why one works and the other doesn't.

One thing to look out for is that (keepGoing = true) and (keepGoing == true) are not the same. If you want to check if keepGoing is true, you should use ==. When you use the single =, you're assigning true to keepGoing, so every time you're trying to check if it's true, you're actually setting it to true.
Also, because while loops are already checking if the condition is true, you could simplify your while statement to just while (keepGoing) {}.

Related

Kotlin - how to use sort function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
Hallo Ladys and Gentleman,
i strugle with a function.
I want convert a given String to a MutableMap.
String:
var testString = "hshhfzrt" + "hszrhhtnt"
function to use:
charMap.toList().sortedByDescending { (_, value) ->
value }.toMap()
Final Output should be a Sorted Char in a new String.
Output example(Not related to testString is just example):
hhh, lll, aaa,
I hope you can help me.
Thx for reading this and your time.
val testString = "hshhfzrt" + "hszrhhtnt"
val result = testString
.toList()
.sorted()
.groupBy { it }
.map { it.value.joinToString("") }
.joinToString(", ")
println(result) // Output: "f, hhhhhh, n, rr, ss, ttt, zz"

How to check array integer value in kotlin? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
i want to make check value function like below code.
enabled is true only if the integer array contains 5 or 16, otherwise enabled is false.
Anyone can help?
Use the default IntArray.any(predicate: (Int) -> Boolean) : Boolean function to check it. Example:
#Test
fun intArray_containsElement() {
val arrayTest = intArrayOf(1, 10, 50, 5, 6, 4, 3)
val isEnable = arrayTest.any { it == 5 || it == 16 }
assertEquals(true, isEnable) // Successfully
}
edit: As Duc Thang pointed out, using any is better because it only iterates the array once:
val IntArray.enabled: Boolean get() = any { it == 5 || it == 16 }
Previous less efficient version:
val IntArray.enabled: Boolean get() = contains(5) || contains(16)
Test:
fun main() {
println(intArrayOf(0).enabled)
println(intArrayOf(0, 5).enabled)
println(intArrayOf(1, 16).enabled)
println(intArrayOf(5, 16).enabled)
println(intArrayOf(19, 1000, 4).enabled)
}
Output:
false
true
true
true
false

Trying to setState using eval() function (React Native)

I'm trying to set multiple states in a for loop to be false or true depending on whether they meet the (if statement) requirement. The for loop will loop through an array of strings, each string represents a state. But I can't seem to use eval within this.setState function...
I have tried researching online but none of the solutions match my problem or what I'm trying to solve. I even tried eval(this.state.anything) = false but it still doesn't work and shows a left hand assign invalid error.
let businessState = [
"this.state.groupName",
"this.state.groupOwnerName",
"this.state.groupDesc",
"this.props.profile._id",
"this.state.businessName",
"this.state.businessDesc",
"this.state.businessRegNo",
"this.state.businessType",
"this.state.businessEmail",
"this.state.businessTel",
"this.state.businessWeChat",
"this.state.businessRegPhotoUri",
"this.state.businessSignPhotoUri"
];
var temp = ""
for (i = 0; i < businessState.length; i++) {
if (eval(businessState[i]) == ""){
temp = businessState[i]+ "Error"
this.setState({
eval(temp): true
})
}
}
As you can see from the code above, I want to evaluate the state, and if the value that this particular state holds is an empty string "", I want to set this state name + "Error" (For example, if this.state.email is empty string "" I want to set this.state.emailError to true.
Instead of this.setState({eval(temp): true}) try this.setState({[temp]: true}). The brackets will output the string value stored in temp as a variable name in setState.
This article gives a good explanation
This Stack Overflow question and the accepted answer also should help

Kotlin - Problems with while()

I was making a calculator in Kotlin and I'm having trouble solving an issue that I'm having with while().On this particular part of the code, I'm trying to find the first operator in the equation, but I need to exclude the ones that indicate whether a number is negative - (or positive +, optional), which need to be indicated between parentheses like so: (-5)
var charay = charArrayOf('+', '-', '*', '/')
var op = 0
var reference = 0
var bol = false
while( bol == false && op != -1){
println(op)
println(bol)
println(bol == false && op != -1)
op = input.indexOfAny(charay, reference)
if (!input.get(op - 1).equals('(')){
bol = true
}else{
reference = op + 1
}
println(op)
println(bol)
println(bol == false && op != -1)
}
To test a normal equation I entered the equation 4+4 and the console looks like this:
0
false
true
1
true
false
0
false
true
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -2
at java.lang.String.charAt(String.java:658)
at CalculatorKt.CalculateValue(Calculator.kt:67)
at CalculatorKt.CalculateValue(Calculator.kt:108)
at CalculatorKt.main(Calculator.kt:119)
Like I suspected, for some reason, the variables reset at the end of the while(), which is the reason why it never leaves said while(). Can anyone tell me why?
Read the error. You're trying to read the character of a string at an index that doesn't exist with this statement:
input.get(op - 1)
You need to check what op is first to make sure it is found. indexOfAny returns -1 if not found in the string. Because we can't see what charay is, we can't help you further.

JSON Array goes crazy [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a huge problem with my two lovely JSON-Arrays.
The code is like:
else if ($range == "day") $sqlRangeString = "GROUP BY DATE_FORMAT(dbtime, '%Y-%c-%e')";
$startdate = doTimeStamp($startdate);
$enddate = doTimeStamp($enddate);
if (isset($consumer_on))
{
echo '[';
$counter = 0;
foreach($consumer_name as $consumer_name_value)
{
$result2 = mysql_query("SELECT AVG(loadvalue) AS m1, dbtime, time
FROM $consumer_name_value
WHERE time >= $startdate
AND time <= $enddate
$sqlRangeString
ORDER BY time") or die('#ä');
while ($data2 = mysql_fetch_array($result2))
{
$consumer_value[$counter][0] = $data2['time'];
if (!isset($consumer_value[$counter][1])) $consumer_value[$counter][1] = 0;
$consumer_value[$counter][1] = (float)$consumer_value[$counter][1] + (float)$data2['m1'];
$counter++;
}
}
echo json_encode($consumer_value);
}
if (isset($producer_on))
{
$ounter = 0;
if (isset($consumer_on) && ($consumer_on == 1))echo ',';
foreach($producer_name as $producer_name_value)
{
$result3 = mysql_query("SELECT AVG(power) AS m1, dbtime, time
FROM $producer_name_value
WHERE time >= $startdate
AND time <= $enddate
$sqlRangeString
ORDER BY time") or die('#ää'); ;
while ($data3 = mysql_fetch_array($result3))
{
$producer_value[$counter][0] = $data3['time'];
if (!isset($producer_value[$counter][1])) $producer_value[$counter][1] = 0;
$producer_value[$counter][1] = $producer_value[$counter][1] + (float)$data3['m1'];
$counter++;
}
}
echo json_encode($producer_value);
}
}
?>
My problem is the output :
Why does the output from the produver_value array has the number in front of each part? How can I remove this?
The "array" has a number before each item because the PHP array indexes don't start from 0. You have an associative array instead of a regular one, which makes json_encode produce a JSON object instead of an array.
It's possible that this happens because of this typo:
$ounter = 0; // should be $counter ?
You can use array_values to extract the values from the array.