code problem

amir zamani 20 Reputation points
2023-02-24T14:34:15.9766667+00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            int x = 90;
            int y = 23;
            int z = x + y;
            Console.WriteLine("X IS : {0}\n Y IS : {1}\n Z IS {3}", x, y, z);    




        }
    }
}

this is my code but when i run it

i getting an error

ike this:

Unhandled Exception: System.FormatException: Input string was not in a correct format.
   at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.IO.TextWriter.WriteLine(String format, Object arg0, Object arg1, Object arg2)
   at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0, Object arg1, Object arg2)
   at System.Console.WriteLine(String format, Object arg0, Object arg1, Object arg2)
   at ConsoleApp1.Program.Main(String[] args) in F:\vscode\ConsoleApp1\ConsoleApp1\Program.cs:line 16

how should i sloved this problem?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,010 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,436 Reputation points
    2023-02-24T15:02:37.69+00:00

    The param {3} should had been {2}

    Try this

    int x = 90;
    int y = 23;
    int z = x + y;
    Console.WriteLine($"X IS : {x}\n Y IS : {y}\n Z IS {z}");
    

    Or

    int x = 90;
    int y = 23;
    int z = x + y;
    Console.WriteLine("X IS : {0}\n Y IS : {1}\n Z IS {2}", x, y, z);
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Alan Farias 750 Reputation points
    2023-02-24T15:02:02.7033333+00:00

    The error in this code is in the last line where you are trying to format the output string using "{3}" as a placeholder for the third argument.

    The correct syntax for the placeholders is to use zero-based indices starting from 0. Therefore, the third argument should be referenced using "{2}" instead of "{3}".

    Here's the corrected code:

    int x = 90;
    int y = 23;
    int z = x + y;
    
    Console.WriteLine("X IS : {0}\n Y IS : {1}\n Z IS {2}", x, y, z);
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.