I am trying to do this lab exercise with the below solution to the provided question but unable to complete it. Please let me know where I am wrong

Q ] PatternMatching takes the integer input from command line. Based on the input, write a code using match to print Negative/Zero is input when input is less than or equal to 0.
Print Even number is given when input is even, and print Odd number is given when input is odd.

Solution:
object PatternMatching{
def main(args :Array[String]){
val input :Int = args(0).toInt
input match {
case 1 if input == 0 => println(“Negative/Zero is input”)
case 2 if input % 2 == 0 => println(“Even number is given”)
case 3 if input % 2 != 0 => println(“Odd number is given”)
}
}
}

Compile the program using:

scalac PatternMatching.scala

Execute the program to print the outputs:

scala PatternMatching.scala 3

Output will be: Odd number is given

When posting code,

  • Please use Markdown so that the code is properly formatted. Otherwise it’s hard to read, which makes it hard to help you, which means you’ll get less help.
  • Don’t use curly quotes instead of plain quotes. The curly quotes won’t pass the compiler, which means people who want to help you can’t easily paste this code into their environments and try it

As for the substance of your question, I think you are confused about the meaning of case 1. The idea isn’t that you number the cases in order. The idea is that case 1 only matches if the input is 1. The thing immediately after case is a pattern to be matched against. So case 1 if input == 0 is a nonsequitur; input can’t be both 1 and 0. I think you mean just case 0 (without the if part).

To understand match and case syntax, I’d suggest reviewing this page: https://docs.scala-lang.org/tour/pattern-matching.html

2 Likes

I m getting the same error as before , i m posting the code,there are 7 errors and its showing ilegeal character literal, what do I have to do to compile successfully! Can u plz tell me the mistakes here in the same original code which was posted, i just changed to case0, case1 and case2

1 Like

Yes, show us the code and the error message from the compiler please. Otherwise nobody would be able to guess what you did and help you.

1 Like

okay sure can u plz help the flatmap part of the code, i had published it in the forum!
Now no errors,but 3 is not shown as odd no, as in my lab exercise 3 is internally given as value in the command line argument! This is the code for case class with pattern matching!

objectPatternMatching{
def main(args :Array[String]){
val input :Int = args(0).toInt
input match {
case 0 if input == 0 => println(“Negative/Zero is input”)
case 1 if input % 2 == 0 => println(“Even number is given”)
case 2 if input % 2 != 0 => println(“Odd number is given”)
}
}
}

Output should come as Odd number is given when i give 3 as input!

Obviously your code only matches for with input 0, 1 or 2. Perhaps you should begin with (input % 2) match

You seem to be still confused about how the match expression works.

When you write:

input match {
  case 1 => println(...)
}

then this case can only be hit when input matches 1, i.e. when input equals 1!

Guarding the case with an additional if, only further constrains the condition that must be met before it is considered a match.

In your code, you only have three possible values that are ever matched: 0, 1, and 2 (put aside the guard conditions). For any other input value there is just no clause that will match at all, and you will receive a MatchError exception at runtime.

One possible way to solve this is to introduce a variables in each clause and check that instead of some fixed value:

input match {
  case number if ... => ...
  .
  .
  .
}
1 Like

How to do that, can u plz send the example for the code,just pls show me?

can u plz wait online i will send u the error again after writing the code!

What you are saying just can’t be. You can’t have input 3 since there is no case for 3.

The syntax of the match stmt is incorrect. Do a Google search on “match in Scala”

On my computer, all the quote characters are illegal Unicode chars.

You want to match on (input % 2) or (input & 1) to determine parity.

CElliott

The Expression abstract class is created with 4 other case classes. Write a function which takes an Expresssion object as input, and use match so that when an Expression object is taken:

  1. It is a number is printed for Number object.
  2. It is a string expression is printed for Var object.
  3. It is a unary operation is printed for UnOp object.
  4. It is a binary operation is printed for BinOp object.
  5. Invalid Expression is printed in all other cases.

Copy the following CaseClass program into the file: abstract class Expression case class Var(name: String) extends Expression case class Number(num: Double) extends Expression case class UnOp(operator: String, arg: Expression) extends Expression case class BinOp(operator: String, left: Expression, right: Expression) extends Expression object CaseClassMatching extends App { val op = BinOp("+", Number(1), Number(4)) describe(op) def describe //write your code here } } After copying, press Esc followed by :wq to save the file.

Compile the program using:

scalac CaseClass.scala

Execute the program to print the outputs:

scala CaseClassMatching

Output will be: It is a binary operation

Please open a new topic for a new question. But, be aware that this is no place to simply dump your homework assignments and receive a solution. We help (voluntarily) if you show some effort to solve it yourself (show what you did, where you got stuck, any errors et cetera), but not even formatting your message in a readable way has quite the opposite effect.

1 Like

ya this is the question! I coded like this

[quote=“Scala_learner, post:1, topic:5868”]
object PatternMatching{
def main(args :Array[String]){
val input :Int = args(0).toInt
input match {
case 1 if input < 0 || input ==0 => println(“Negative/Zero is input”)
case 2 if input % 2 == 0 => println(“Even number is given”)
case _ if input % 2 != 0 => println(“Odd number is given”)
}
}
}
this is the correct code

Hi Did you get the correct answer of this question

Sir , for this question iam getting run time error only when I give input negative number and zero only .
My code
def patternmatch(var1:Int)=var1 match{
Case 1 if (var1<= 0)
=>println(“Negative/Zero is given”)
Similarly when other two cases iam getting correct output i.e even and odd.

Have u got this crct code?

I have been trying to run the following code but a std err shows up for two of the test cases

object Result {

/*
 * Complete the 'PatternMatching' function below.
 *
 * The function accepts INTEGER var1 as parameter.
 */

def PatternMatching(var1: Int) = var1 match {




    case 1 if var1 == 0 || var1 < 0 => println("Negative/Zero")
    case 2 if var1 % 2 == 0 => println("Even number is given")
    case _ if var1 % 2 != 0 => println("Odd number is given")

}
}

object Solution {
def main(args: Array[String]) {
val var1 = StdIn.readLine.trim.toInt

    Result.PatternMatching(var1)
}

}

This is the stderr that shows up
Error (stderr)

  • scala.MatchError: 0 (of class java.lang.Integer)

  • at Result$.PatternMatching(Solution.scala:37)

  • at Solution$.main(Solution.scala:49)

  • at Solution.main(Solution.scala)

  • at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

  • at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

  • at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

  • at java.lang.reflect.Method.invoke(Method.java:498)

  • at scala.reflect.internal.util.ScalaClassLoader.$anonfun$run$2(ScalaClassLoader.scala:105)

  • at scala.reflect.internal.util.ScalaClassLoader.asContext(ScalaClassLoader.scala:40)

  • at scala.reflect.internal.util.ScalaClassLoader.asContext$(ScalaClassLoader.scala:37)

  • at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.asContext(ScalaClassLoader.scala:130)

  • at scala.reflect.internal.util.ScalaClassLoader.run(ScalaClassLoader.scala:105)

  • at scala.reflect.internal.util.ScalaClassLoader.run$(ScalaClassLoader.scala:97)

  • at scala.reflect.internal.util.ScalaClassLoader$URLClassLoader.run(ScalaClassLoader.scala:130)

  • at scala.tools.nsc.CommonRunner.run(ObjectRunner.scala:29)

  • at scala.tools.nsc.CommonRunner.run$(ObjectRunner.scala:28)

  • at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:43)

  • at scala.tools.nsc.CommonRunner.runAndCatch(ObjectRunner.scala:35)

  • at scala.tools.nsc.CommonRunner.runAndCatch$(ObjectRunner.scala:34)

  • at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:70)

  • at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:91)

  • at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:103)

  • at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:108)

  • at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)

Change case 1 and case 2 to case _.

In your example you are matching the value of input to values of 1, 2 and to anything else in the last case. That’s not what you want to do. You need to match against a new variable and then compare. Something like this:

def PatternMatching(var1: Int): String = var1 match {
  case i if i <= 0 => "Negative/Zero"
  case i if i % 2 == 0 => "Even number is given"
  case _ => "Odd number is given"
}
1 Like