Can anybody help me to write ternary operator code for following code
if(s> b)
{
minlength = s.length;
maxlength = b.length;
}
else
{
minlength = b.length;
maxlength = s.length;
}
i have tried the following code but it gives me an error
s.Length > B.Length ? ( minlength = B.Length,maxlength = s.Length ) : ( minlength = s.Length, maxlength = B.Length);
when i use above code it gives an error
"only assignment call increment decrement and new object expressions
can be used as a statement"
Can anybody help me to resolve this...
why just write it in this way :
minlength = (s > b) ? s.length : b.length;
maxlength = (s > b) ? b.length : s.length;
Do you really need to use a ternary operator? I would have thought that a simple Math.Min/Max would be clearer to anyone reading it:
minlength = Math.Min(s.length, b.length);
maxlength = Math.Max(s.length, b.length);
...but that's just me :-)
Related
I'm trying to do a type checking on an input that the user insert, but I don't know ho to do.
My code is:
for(iteration<- 0 to 19) {
print(movieRecommended(iteration))
var personalRate = scala.io.StdIn.readDouble()
if(Try(personalRate.toInt).isSuccess){
while((personalRate > 5 || personalRate < 1) || personalRate % 0.5 != 0) {
println("Error: respect the parameters")
print(movieRecommended(iteration))
personalRate = scala.io.StdIn.readDouble()
}
}
else println("Error")
ratingArr(iteration) = personalRate
}
But when I try to give a string input like "a" I receive this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "a"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:549)
at scala.collection.immutable.StringLike.toDouble(StringLike.scala:321)
at scala.collection.immutable.StringLike.toDouble$(StringLike.scala:321)
at scala.collection.immutable.StringOps.toDouble(StringOps.scala:33)
at scala.io.StdIn.readDouble(StdIn.scala:167)
at scala.io.StdIn.readDouble$(StdIn.scala:162)
at scala.io.StdIn$.readDouble(StdIn.scala:241)
at CollaborativeFilteringUserBasedALS$.$anonfun$askUserInput$1(CollaborativeFilteringUserBasedALS.scala:192)
at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:158)
at CollaborativeFilteringUserBasedALS$.askUserInput(CollaborativeFilteringUserBasedALS.scala:189)
at CollaborativeFilteringUserBasedALS$.topRated(CollaborativeFilteringUserBasedALS.scala:133)
at CollaborativeFilteringUserBasedALS$.main(CollaborativeFilteringUserBasedALS.scala:284)
at CollaborativeFilteringUserBasedALS.main(CollaborativeFilteringUserBasedALS.scala)
Someone can explain me what I'm doing wrong?
You can read the input as a string using scala.io.StdIn.readLine() then try to parse it to Int and use pattern matching to handle case for valid int and for error.
Something like this :
for (iteration <- 0 to 19) {
var personalRate = scala.io.StdIn.readLine()
Try(personalRate.toInt).toOption match {
case Some(rate) => {
println(rate)
// your logic for int
}
case _ => println("Error")
//...
}
}
I'm trying to find whether the character "S" or "C" appears in a string. At least one will be in the string but not necessarily both.
let S = codeZ.characters.index(of: "S")
let C = codeZ.characters.index(of: "C")
if (C == nil) || S < C {
nextView.sequential_flag = true
nextView.continuous_flag = false
}
else if S == nil || (C < S) {
nextView.sequential_flag = false
nextView.continuous_flag = true
}
I'm getting the error : Binary operator '<' cannot be applied to two 'String.CharacterView.Index?' (aka 'Optional') operands
In my experience with swift this usually means something else if wrong.
Also I've tried changing the if statements to this below.
if (C == nil) || S?.encodedOffset < C?.encodedOffset {
nextView.sequential_flag = true
nextView.continuous_flag = false
}
And I got the error : Binary operator '<' cannot be applied to two 'Int?' operands.
Any help on how to do this is much appreciated, thank you.
You should check if S is nil or not and provide a fallback value to C. Then you can compare the two non-optional values.
if let S = S, S.encodedOffset < (C?.encodedOffset ?? Int.max) {
nextView.sequential_flag = true
nextView.continuous_flag = false
}
def guessing_game():Unit = {
println("Welcome to the guessing game!!")
val guess_count:Int = 0
val answer = Random.nextInt(50)
var guess_num = scala.io.StdIn.readLine("Input your guess number > ").toInt
while(guess_num != answer || guess_count < 5){
====> guess_count += 1 // <==============================
var situation = if(guess_num > answer){"Your guess is higher!"}else{"Your guess is lower!"}
println(situation)
guess_num = scala.io.StdIn.readLine("Input your guess number > ").toInt
}
if(guess_num == answer){
println("Congratulation....You win!!")
}else{
println("You hav run out of guess!")
}
It says:
Error:(16, 25) value += is not a member of Int
Expression does not convert to assignment because receiver is not assignable.
guess_count.toInt += 1
guess_count is immutable, (val), you cannot change it. Use var if you need to change the variable.
you can increment in scala, but the wrong is you are incrementing and re assigning the value to a final variable, that's why it's throwing error, please change the declaration as below then it will work
var guess_count:Int = 0
Thanks
I am downgrading Swift code from Xcode 8.3.1 to Xcode 7.3.1.
The Swift compiler of Xcode 7.3.1 raises
Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
while pointing on line zeroParameterAndPaths.sort {. The code was ok in Xcode 8.3.1.
What's wrong and how to fix it?
class NewConnectingSegmentZeroParameterAndPath {
let step : Int; // 0 = main, 1 = first outline, 2 = second outline
let parameter : CGFloat;
init(step: Int, parameter: CGFloat) {
self.step = step;
self.parameter = parameter;
}
}
var zeroParameterAndPaths : [NewConnectingSegmentZeroParameterAndPath] = [];
// ... some zeroParameterAndPaths .appendContentsOf calls
zeroParameterAndPaths.sort {
return $0.parameter < $1.parameter
|| ($0.parameter == $1.parameter
&& ($0.step == 1 || ($0.step == 0 && $1.step == 2))
)
};
You have two choices. One is simply to do what the error message suggests, i.e. pulling the complex bool apart into separate pieces:
zeroParameterAndPaths.sort {
let bless = ($0.parameter < $1.parameter)
let beq = ($0.parameter == $1.parameter)
let band = ($0.step == 0 && $1.step == 2)
let bor = ($0.step == 1 || band)
let beqandbor = (beq && bor)
return (bless || beqandbor)
};
The other is to provide an explicit in line giving the param types and result type:
zeroParameterAndPaths.sort {
(a:NewConnectingSegmentZeroParameterAndPath, b:NewConnectingSegmentZeroParameterAndPath) -> Bool in
return a.parameter < b.parameter
|| (a.parameter == b.parameter
&& (a.step == 1 || (a.step == 0 && b.step == 2))
)
};
You could also make your class a little bit more helpful and make it implement the condition. The compiler is much less likely to get confused in a function body than in a closure:
class NewConnectingSegmentZeroParameterAndPath {
let step : Int; // 0 = main, 1 = first outline, 2 = second outline
let parameter : CGFloat;
init(step: Int, parameter: CGFloat) {
self.step = step;
self.parameter = parameter;
}
func orderedBefore(_ other: NewConnectingSegmentZeroParameterAndPath) -> Bool
{
return parameter < other.parameter
|| parameter == other.parameter
&& (step == 1 || step == 0 && other.step == 2)
}
}
var zeroParameterAndPaths : [NewConnectingSegmentZeroParameterAndPath] = [];
// ... some zeroParameterAndPaths .appendContentsOf calls
zeroParameterAndPaths.sort { $0.orderedBefore($1) }
Apart from the issue of the type inference engine not being able to quickly resolve such complex bool expressions, such expressions are really hard to follow. I suggest you break it down into something simpler, like so:
zeroParameterAndPaths.sort {
if $0.parameter != $1.parameter { return $0.parameter < $1.parameter ]
if $0.step == 1 { return true }
if $0.step == 0 && $1.step == 2 { return true }
return false
};
There's my attempt at it. I'm not even sure if it's correct, the original expression is pretty hard to follow.
I'm currently converting C++ code to Swift and I've gotten stuck on one part. The parameter passed into the function is a string and the area where I'm stuck is when attempting to set a variable based on the second to last character of a string to check for a certain character.
The error shows up on this line:
line[i-1]
I've tried casting this value to an Int but this didn't work:
Int(line[i - 1])
I've also tried to see if the string's startIndex function which takes a Int would work but it didn't:
line.startIndex[i - 1]
Here is the full function:
func scanStringForSpecificCharacters(line: String){
var maxOpen: Int = 0;
var minOpen: Int = 0;
minOpen = 0;
maxOpen = 0;
var i = 0
while i < line.characters.count {
for character in line.characters {
//var c: Character = line[i];
if character == "(" {
maxOpen += 1;
if i == 0 || line[i - 1] != ":" {
minOpen += 1;
}
}
else if character == ")"{
minOpen = max(0,minOpen-1);
if i == 0 || line[i-1] != ":"{
maxOpen -= 1;
}
if maxOpen < 0{
break;
}
}
}
if maxOpen >= 0 && minOpen == 0{
print("YES")
}else{
print("NO")
}
}
}
Strings in Swift aren't indexed collections and instead you can access one of four different views: characters, UTF8, UTF16, or unicodescalars.
This is because Swift supports unicode, where an individual characters may actually be composed of multiple unicode scalars.
Here's a post that really helped me wrap my head around this: https://oleb.net/blog/2016/08/swift-3-strings/
Anyway, to answer you question you'll need to create an index using index(after:), index(before:), or index(_, offsetBy:).
In your case you'd want to do something like this:
line.index(line.endIndex, offsetBy: -2) // second to last character
Also, you'll probably find it easier to iterate directly using a String.Index type rather than Int:
let line = "hello"
var i = line.startIndex
while i < line.endIndex {
print(line[i])
i = line.index(after: i)
}
// prints ->
// h
// e
// l
// l
// o
Working with Strings in Swift was changed several times during it's evolution and it doesn't look like C++ at all. You cannot subscript string to obtain individual characters, you should use index class for that. I recommend you read this article:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html
As already pointed out in the other answers, the compiler error
is caused by the problem that you cannot index a Swift String with
integers.
Another problem in your code is that you have a nested loop which is
probably not intended.
Actually I would try to avoid string indexing at all and only
enumerate the characters, if possible. In your case, you can
easily keep track of the preceding character in a separate variable:
var lastChar: Character = " " // Anything except ":"
for char in line.characters {
if char == "(" {
maxOpen += 1;
if lastChar != ":" {
minOpen += 1;
}
}
// ...
lastChar = char
}
Or, since you only need to know if the preceding character is
a colon:
var lastIsColon = false
for char in string.characters {
if char == "(" {
maxOpen += 1;
if !lastIsColon {
minOpen += 1;
}
}
// ...
lastIsColon = char == ":"
}
Another possible approach is to iterate over the string and a shifted
view of the string in parallel:
for (lastChar, char) in zip([" ".characters, line.characters].joined(), line.characters) {
// ...
}
As others have already explained, trying to index into Swift strings is a pain.
As a minimal change to your code, I would recommend that you just create an array of the characters in your line up front:
let linechars = Array(line.characters)
And then anywhere you need to index into the line, use linechars:
This:
if i == 0 || line[i-1] != ":" {
becomes:
if i == 0 || linechars[i-1] != ":" {