简体   繁体   中英

Unhandled Exception: System.FormatException: Input string was not in a correct format

I'm trying to get this small movie ratings program to work properly with everything going fine until I start prompting for the ratings that the reviewer would enter. It lets me rate both acting fine but as soon as I hit the enter button to rate music is will move down to a blank line instead of prompting for the next input. The only way I to get around this seems for me to enter the value twice.

thanks

Console.WriteLine("Rate the following out of 5");
Console.Write("Acting > ");
acting_rating = int.Parse(Console.ReadLine());

Console.Write("Music > ");
Console.ReadLine();
music_rating = int.Parse(Console.ReadLine());

Console.Write("Cinematography > ");
Console.ReadLine();
cinematography_rating = int.Parse(Console.ReadLine());

Console.Write("Plot > ");
Console.ReadLine();
plot_rating = int.Parse(Console.ReadLine());

Console.Write("Duration > ");
Console.ReadLine();
duration_rating = int.Parse(Console.ReadLine());

you call Console.ReadLine(); one time too often... just remove the Console.ReadLine(); between Console.Write and the int.Parse .

Although IF the user enters anthing wrong - like a word instead of a number - you will still get an exception... To handle that properly use a try catch block and/or TryParse .

Excluding Acting, you have always two Console.ReadLine(); ie :

Console.Write("Music > ");  // write Music > 
Console.ReadLine();         // read the user input (and throw it away)
music_rating = int.Parse(Console.ReadLine()); // read the user input again and parse it

Remove the single statement Console.ReadLine(); and should be ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM