简体   繁体   English

c# 如何修复:“未处理的异常:System.FormatException:输入字符串的格式不正确。”

[英]c# How Can I Fix: “Unhandled Exception: System.FormatException: Input string was not in a correct format.”

I need help understanding why my ID input is being considered in the wrong format.我需要帮助了解为什么我的 ID 输入被认为是错误的格式。

I'll insert the area and the full code as well just in case.为了以防万一,我也会插入该区域和完整的代码。

Code:代码:

static void AmendPrice(List<TSweet> sweets)
{
      Console.ForegroundColor = ConsoleColor.White;
      Console.WriteLine();

      Console.WriteLine("Enter ID:");
      string id = Convert.ToString(Console.ReadLine());

      TSweet  Sweet1 = new TSweet();
      string nid = "";
      string ns = "";
      Single np = Convert.ToSingle("");
      int ind = 0;

      foreach (TSweet Sweet in sweets)
      {
          nid = Sweet.productID;
          ns = Sweet.SweetName;
          np = Sweet.Price;
          ind = Convert.ToInt32(sweets.IndexOf(Sweet));

          if (Sweet.productID == id)
          {
              Console.WriteLine("Found\nEnter New Price:");
              np = Convert.ToSingle(Console.ReadLine());
          }
          else
          {
              Console.WriteLine("Not Found");
          }
      }
}

Full code:完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ListOfSweets
{
    class Program
    {
        struct TSweet
        {
            public string productID;
            public string SweetName;
            public Single Price;
        }

        static void AddNewSweet(List<TSweet> sweets)
        {
        Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("\n\nEnter Product ID:");
            string newid = Convert.ToString(Console.ReadLine());
            Console.WriteLine("\nEnter Sweet Name:");
            string news = Convert.ToString(Console.ReadLine());
            Console.WriteLine("\nEnter Price:");
            Single newp = Convert.ToSingle(Console.ReadLine());
            TSweet  Sweet = new TSweet();
            Sweet.productID = newid;
            Sweet.SweetName = news;
            Sweet.Price = newp;
            sweets.Add(Sweet);
        }

        static void ListSweets(List<TSweet> sweets)
        {
              Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\n\nThe list contains:");
            foreach (TSweet Sweet in sweets)
            {
                  Console.WriteLine("ID:" + Sweet.productID + "\n"+ "Name:" + Sweet.SweetName + "\n" + "Price:" + Sweet.Price + "\n");
              }
        }

        static void AmendPrice(List<TSweet> sweets)
        {
          Console.ForegroundColor = ConsoleColor.White;
          Console.WriteLine();
          Console.WriteLine("Enter ID:");
          string id=Convert.ToString(Console.ReadLine());
          TSweet  Sweet1 = new TSweet();
          string nid = "";
          string ns = "";
          Single np = Convert.ToSingle("");
          int ind=0;
          foreach (TSweet Sweet in sweets)
          {
            nid = Sweet.productID;
            ns = Sweet.SweetName;
            np = Sweet.Price;
            ind = Convert.ToInt32(sweets.IndexOf(Sweet));
            if (Sweet.productID == id)
            {
              Console.WriteLine("Found\nEnter New Price:");
              np = Convert.ToSingle(Console.ReadLine());
            }
            else
            {
              Console.WriteLine("Not Found");
            }
          }
          Sweet1.productID = nid;
          Sweet1.SweetName = ns;
          Sweet1.Price = np;
          sweets.RemoveAt(ind);
          sweets.RemoveAt(ind+1);
          sweets.RemoveAt(ind+2);
          sweets.Add(Sweet1);
        }

        static void DisplayMenu()
        {
              Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("\n\n==== MENU ====");
            Console.WriteLine("1.. Add new sweet");
            Console.WriteLine("2.. Display all sweets");
            Console.WriteLine("3.. Amend price");
            Console.WriteLine("q.. Quit program");
            Console.WriteLine("\nEnter menu option: ");
        }

        static void Main(string[] args)
        {
            List<TSweet> sweets = new List<TSweet>();
            string choice = "";
            while (choice != "q")
            {
                DisplayMenu();
                choice = Console.ReadLine().ToLower();
                switch (choice)
                {
                    case "1":
                        AddNewSweet(sweets);
                              break;
                    case "2":
                        ListSweets(sweets);
                              break;
                    case "3":
                        AmendPrice(sweets);
                        break;
                    default:
                        if (choice != "q")
                            Console.WriteLine("Invalid option entered.");
                        break;
                }
            }
        }
    }
}

As pointed in the comments by @Jamiec the prolem is in the line Single np = Convert.ToSingle("");正如@Jamiec 在评论中指出的那样,问题位于Single np = Convert.ToSingle(""); , "" is not a valid Single so the conversion fails, if you ment 0 just write 0 . , ""不是有效的Single因此转换失败,如果您输入0只需写入0
But that's a small part of the bigger problem, you have too many conversions ( Convert.To... ) and most of them aren't needed.但这只是更大问题的一小部分,您有太多的转换( Convert.To... ),而且大多数都不需要。 The examples I could find are:我能找到的例子是:

  1. Convert.ToString(Console.ReadLine()) - Console.ReadLine() is already a string, there's no need for convertion. Convert.ToString(Console.ReadLine()) - Console.ReadLine()已经是一个字符串,不需要转换。
  2. Convert.ToInt32(sweets.IndexOf(Sweet)) - sweets.IndexOf(Sweet) is already an int, there's no need for convertion. Convert.ToInt32(sweets.IndexOf(Sweet)) - sweets.IndexOf(Sweet)已经是一个 int,不需要转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#当我使用TryParse时,为什么会收到“未处理的异常:System.FormatException:输入字符串的格式不正确。” - C# Why I get “Unhandled Exception: System.FormatException: Input string was not in a correct format.” when I use TryParse? System.FormatException:输入字符串的格式不正确。 c# - System.FormatException: Input string was not in a correct format. c# C# 错误 System.FormatException: &#39;输入字符串的格式不正确。&#39; 在数字输入上 - C# Error System.FormatException: 'Input string was not in a correct format.' on number input 类型为“ System.FormatException”的未处理的异常输入字符串的格式不正确 - Unhandled exception of type “System.FormatException” Input string was not in correct format 未处理的异常:System.FormatException:输入字符串的格式不正确 - Unhandled Exception: System.FormatException: Input string was not in a correct format 错误:未处理的异常:System.FormatException:输入字符串的格式不正确 - Error: Unhandled Exception: System.FormatException: Input string was not in a correct format 我得到了这个异常:System.FormatException:'输入字符串的格式不正确。' - I got this exception: System.FormatException: 'Input string was not in a correct format.' System.FormatException: &#39;输入字符串的格式不正确。&#39; 在 C# 黄皮书教科书中 - System.FormatException: 'Input string was not in a correct format.' in C# Yellowbook textbook C# Excel combobox 中的空行(导致错误“System.FormatException:输入字符串格式不正确。”) - C# Excel empty rows in combobox (causing error “System.FormatException:Input string was not in a correct format.”) System.FormatException: &#39;输入字符串的格式不正确。&#39; - System.FormatException: 'Input string was not in a correct format.'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM