How to solve a string formatting error?

0

I was normally programming in VS in "Console" mode when I come across this message:

  

"A first chance exception of type 'System.FormatException' occurred in mscorlib.dll   An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll   Additional information: Index (zero-based) must be greater than or equal to zero and smaller than the argument list size.   The program '[1124] ConsoleApplication4.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0) "

What is it about and how do I solve it?

Code:

string A1;
string A2;
string A3;
string A4;
string A5;
String A6;
String A7;
String A8;


A1 = Console.ReadLine();
A2 = Console.ReadLine();
A3 = Console.ReadLine();
A4 = Console.ReadLine();
A5 = Console.ReadLine();
A6 = Console.ReadLine();
A7 = Console.ReadLine();
A8 = Console.ReadLine();

Console.Write("Segunda: {0}, {1}, {2}, {3}", A1, A2, A3, A4);
Console.ReadLine();
Console.Write("Terça: {4}, {7}, {5}, {1}, {6}", A5, A8, A6, A2, A7); 

Console.ReadKey();
    
asked by anonymous 10.02.2017 / 04:57

2 answers

7

The problem is that you've placed a argument number that does not exist. This numbers inside the keys is the number in the order that comes after the formatting text arguments. The first will always be 0 and will, 1, 2, and so on as many as you have, then the last will be the amount of arguments passed minus 1. If you passed 4, they range from 0 to 3. You can not use the numbers you used. The error occurred because it could not find a number 4 argument. The string formatting has problems in this context, so it throws a runtime exception.

But we can do it simpler and avoid this error. We can modernize this code by simplifying it a lot. You do not need to declare the variable before assigning a value to it, you do not need to type the variable, and you do not need to pass arguments after the string .

Use var to make inference, using static to import the static class, and string to use arguments within string . That's better:

using static System.Console;

public class Program {
    public static void Main() {
        var A1 = ReadLine();
        var A2 = ReadLine();
        var A3 = ReadLine();
        var A4 = ReadLine();
        var A5 = ReadLine();
        var A6 = ReadLine();
        var A7 = ReadLine();
        var A8 = ReadLine();
        Write($"Segunda: {A1}, {A2}, {A3}, {A4}");
        ReadLine();
        Write($"Terça: {A5}, {A8}, {A6}, {A2}, {A7}");
    }
}

See running on .NET Fiddle . And at Coding Ground . Also I put it in GitHub for future reference .

    
10.02.2017 / 11:09
5

Your error is in this line:

Console.Write("Terça: {4}, {7}, {5}, {1}, {6}", A5, A8, A6, A2, A7);

The indexes in this Console.Write should start at 0 and go up to the maximum number of parameters minus 1. To correct, just change the indexes of the writing parameters, like this:

Console.Write("Terça: {0}, {1}, {2}, {3}, {4}", A5, A8, A6, A2, A7);
    
10.02.2017 / 09:40