-1

I don't know C# but I have homework to convert from Java to C# or C and I have found an online converter, but when I put the code to C# compiler, I get this error

main.cs(35,34): error CS1041: Identifier expected, `in' is a keyword

This is my C# code:

using System;

public class JavaApplication
{
    public static void selectionSort(int[] arr)
    {
        for (int i = 0; i < arr.Length - 1; i++)
        {
            int index = i;

            for (int j = i + 1; j < arr.Length; j++)
            {
                if (arr[j] < arr[index])
                {
                    index = j; //searching for lowest index
                }
            }

            int smallerNumber = arr[index];

            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }
    }

    public static void Main(string[] a)
    {
        int[] arr1 = new int[10];
        Scanner scan = new Scanner(System.in);
        Console.WriteLine("Before Selection Sort:");

        for (int i = 0; i < 10; i++)
        {
            arr1[i] = scan.Next();
        }

        selectionSort(arr1);

        Console.WriteLine("After Selection Sort");

        foreach (int i in arr1)
        {
           Console.Write(i + " ");
        }

        Console.WriteLine("");
        int sumEven = 0;
        int sumOdd = 0;

        for (int j = 0; j < 10; j++)
        {
           if (arr1[j] % 2 == 0)
           {
               sumEven++;
           }
           else
           {
               sumOdd++;
           }
        }

        Console.WriteLine("The number of even numbers in this array is:" + sumEven);
        Console.WriteLine("The number of odd numbers in this array is:" + sumOdd);
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

This line is causing the error:

Scanner scan = new Scanner(System.in);

System.in doesn't mean anything in C#, hence it is complaining because it is looking for a class named in in the System namespace.

In Java console application, System.in is typically the input buffer (keyboard).

In C#, to read a line from the Console, instead of Scanner (which doesn't exist), you can use Console.ReadLine(). Of course it's not clear what is being read in your application (numbers?) so you may need to do some type conversion as ReadLine() returns a string?.

Edit following OP request to read numbers from Console

OP asked how to replace the existing Java code that reads numbers from the console with the C# equivalent. Here is one suggestion (there are several approaches that accomplish the same):

int[] arr1 = new int[10];
Console.WriteLine("Before Selection Sort:");

for (int i = 0; i < 10; i++)
{
    string text = Console.ReadLine();

    if (text != null && int.TryParse(text, out int value))
        arr1[i] = value;
    else
        Console.WriteLine("You must enter a valid number. Try again.");
}
Martin
  • 16,093
  • 1
  • 29
  • 48