Prasanth Sai Prasanth Sai - 1 year ago 89
C# Question

string using conditional operator in c#

My program output should print whether or not

is weird. I tried the below code but when I run the code it is throwing an error like "Can only use array initializer expressions to assign to array types. Try using a new expression instead". Can someone correct the code. Thanks in advance.

These are the rules:
If N is odd, print Weird
If N is even and in the inclusive range of 2 to 5, print Not Weird
If N is even and in the inclusive range of 6 to 20 , print Weird
If N is even and greater than 20, print Not Weird

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution
static void Main(String[] args)
int N = Convert.ToInt32(Console.ReadLine());
string s = {(N%2 !=0 ? "Weird" : (N>20 ? "Not Weird" : ((N > 1 && N <6) ? "Not Weird" : "Weird")))};

Answer Source

Your error is because, well... you are using an array initialiser as it says.

When you instantiate the string, using {} is initialising an array, instead you should be removing that part entirely and using

string s = (N%2 !=0 ? "Weird" : (N>20 ? "Not Weird" : ((N > 1 && N <6) ? "Not Weird" : "Weird")));

The array initialiser can be used for strings, but only if you are making a char array

string s = new char[] { 'H', 'e', 'l', 'l', 'o', };
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download