Newb继承受挫 [英] Newb inheritance frustration

查看:93
本文介绍了Newb继承受挫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我在这个程序上正在做的一切,但它仍然在吐出错误。我现在对此感到非常沮丧,我只需要别人看一下。

我认为这个问题很容易就像在错误的地方一样,但是我遇到了很多错误。

我只是想了解继承!我没有做足够长的代码来自行调试这个东西,它可能就像我之前说过的那样简单,但是我为一个简单的程序得到了40个错误。



 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;

命名空间 BookConsole
{
class Program
{
静态 void Main()
{
public string 输入;
Console.WriteLine( 你想要一本书,一本教科书或一本咖啡桌书吗? /跨度>);
string input = Console.ReadLine();

if (input == book
{
预订myBook = Book();

Console.WriteLine( 输入标题);
myBook.Title = Convert.ToString(Console.ReadLine());
Console.WriteLine( 作者?);
myBook.Author = Convert.ToString(Console.ReadLine());
Console.WriteLine( 输入价格);
myBook.Price = Convert.ToDouble(Console.ReadLine());
Console.WriteLine( 这是书{0}标题:{1}撰写者:{2}价格:{3},myBook.BookNumber,myBook.Title,myBook.Author,myBook.Price);
}
else if (input == textbook
{
TextBook myText = new TextBook();
Console.WriteLine( 输入成绩等级);
myText.Grade = Convert.ToString(Console.ReadLine());
Console.WriteLine( 输入标题);
myText.Title = Convert.ToString(Console.ReadLine());
Console.WriteLine( 作者?);
myText.Author = Convert.ToString(Console.ReadLine());
Console.WriteLine( 输入价格);
myText.Price = Convert.ToDouble(Console.ReadLine());
Console.WriteLine( 这是书{0}标题:{1}撰写者:{2}价格:{3}年级:{4},myText.BookNumber,myText.Title,myText.Author,myText.Price,myText.Grade);
}
else
{
CoffeeTableBook myCoffee = new CoffeeTableBook();

Console.WriteLine( 输入标题);
myCoffee.Title = Convert.ToString(Console.ReadLine());
Console.WriteLine( 作者?);
myCoffee.Author = Convert.ToString(Console.ReadLine());
Console.WriteLine( 输入价格);
myCoffee.Price = Convert.ToDouble(Console.ReadLine());
Console.WriteLine( 这是书{0}标题:{1}撰写者:{2}价格:{3},myCoffee.BookNumber,myCoffee.Title,myCoffee.Author,myCoffee.Price);
}
}
}
静态 class 预订
{
public double 价格;
public int BookNumber { get ; set ; }
public string 标题{ get ; set ; }
public string 作者{ get ; set ; }
public virtual double 价格{获取; set ; }
}
静态 TextBook:预订
{
public 覆盖 double 价格{
获取 {返回价格; }
set {
if value < 20 00 || value > 80 00
{
Console.WriteLine( 价格无效。);
}
else
{
Console.WriteLine( 有效价格);
price = value ;
}
}
}
public char 等级{获取; set ; }
}
静态 CoffeeTableBook:预订
{
public 覆盖 double 价格
{
获取 {返回价格; }
set {
if value < 35 00 || value > 100 00
{
Console.WriteLine( 无效价格。);
}
else
{
Console.WriteLine( 有效价格);
price = value ;
}
}
}
}
}





我尝试过的事情:



在过去的5天里,我尝试过改变curley括号的位置,在不同的区域添加和删除它们。我认为我的类,继承和if-else语句都是正确的。我沮丧地把所有的东西都公之于众。



我尽我所能调试。

解决方案

< blockquote>你不能创建静态类的实例:

预订myBook =  new  Book(); 



- >从三个book-classes中删除 static 修饰符。



方法中声明的变量不能有修饰符,因为它们是自动且始终只在该方法中可见:

  public   string 输入; 



建议删除 public 来自该变量声明的修饰符,但是:然后在此处重新声明输入

  string  input = Console.ReadLine(); 



- >完全删除输入的第一个声明



TextBook.Grade 的类型为 char ,因此您无法分配字符串

 myText.Grade = Convert.ToString(Console.ReadLine()); 



- >建议的解决方案:

  string  gradeInput = Console.ReadLine(); 
if (gradeInput.Length == 1
{
myText.Grade = gradeInput [ 0 ];
}
其他
{
// < span class =code-comment>处理格式错误的输入(例如错误信息,让用户再试一次)
}





通过这些修改,应该处理所有编译器错误。



然后还有一些其他问题可以被认为是样式/良好实践问题:



- 不要验证属性设置器中的值。替代方法:通过构造函数提供所有值,在那里验证它们,如果值无效,则抛出异常。或者有一个专门的验证方法,如:

  bool  IsValid()
{
// ...
}



(在将这些书籍随后存储到数据库中的应用程序中,将在存储该书之前调用它,如果它无效,则会停止保存过程。因此,在您的情况下它会有点人为。)



- Console.ReadLine()已经返回字符串。因此将其传递到 Convert.ToString(..)是完全多余的:

 Convert.ToString(控制台。 ReadLine()); 





- 为了将字符串转换为其他类型,首选(静态)方法是。相应类型的Parse(..) .TryParse(..)。区别在于.Parse(..)如果成功则返回解析后的值,如果不成功则抛出异常,而.TryParse(..)返回 true 如果成功并放置将值解析为 out -parameter,如果不成功则返回 false 。后者通常是更方便的选择:

  double 价格; 
if (!Double.TryParse(Console.ReadLine(), out price))
{
// 处理格式错误的输入(例如错误消息,让用户再试一次)
}





一本关于C#编程的免费PDF书:使用C#/ Java Books编程简介 [ ^ ]


如果你甚至不想用这种语言写C#,你会有什么期望?#

甚至没有试图理解非常明确的消息编译器。显然,你太早就陷入了挫折。



问题从这一行开始:

  public   string 输入; 



什么你觉得它可能意味着什么?这是类成员声明的语法,即字段。但是您将它置于方法 Main 的实现级别。方法没有成员,只有类型。通过将成员声明转换为变量,删除public将修复它。



此行将搞砸其余代码。从这一点来说,没有什么可讨论的。但是在下面的某行上你有

 静态  class  TextBook:Book 



什么,你没有读到C#和.NET不允许扩展静态类型?这不是编程的一般规则,但在.NET中不允许。这条线搞砸了整个班级。等等...我老老实实地解释了第一个bug,不需要再进一步了。



修复它并继续。



现在,我可以看到两种可能性:1)由于经验不足,你几乎没有随机错误并且无法理解编译器消息,2)你不知道一些非常基本的编程原则而且没有胶合您尝试使用的语言是如何工作的。第二种情况似乎对我更有可能。然后,您应该首先阅读一些关于语言和平台的手册,并解释一般的编程思想,并阅读所有内容,而不必跳过一行。你必须明白,你所需要的只是理解;你不必记住任何东西。但你应该为每一章解决简单的练习,更好地解决所有这些练习,除非你觉得有些练习太琐碎了。这样,大多数人都设法来到启蒙,所以你也可以。



我会添加我的简单规则:不写一行代码你不明白。



-SA


I feel like I am doing everything right on this program but it is still spitting out errors. I am severely frustrated with this right now and I just need someone else to look at it.
I think the problem is something easy like a curley brace in the wrong place but I am getting a ton of errors.
I am just trying to learn about inheritance! I haven't been doing code long enough to properly debug this thing by myself and it's probably something simple like I said before, but I'm getting 40 errors for a simple program.

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

namespace BookConsole
{
    class Program
    {
        static void Main()
        {
            public string input;
            Console.WriteLine("Do you want a book, a textbook, or a coffee table book?");
            string input = Console.ReadLine();

            if (input == "book") 
            {
                Book myBook = new Book();
                 
                Console.WriteLine("Enter Title");
                myBook.Title = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Author?");
                myBook.Author = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Enter price");
                myBook.Price = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("This is book {0} Titled: {1} Written by: {2} Price: {3}", myBook.BookNumber, myBook.Title, myBook.Author, myBook.Price);
            }
           else if (input == "textbook")
            {
                TextBook myText = new TextBook();
                Console.WriteLine("Enter Grade Level");
                myText.Grade = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Enter Title");
                myText.Title = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Author?");
                myText.Author = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Enter price");
                myText.Price = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("This is book {0} Titled: {1} Written by: {2} Price: {3} Grade Level: {4}", myText.BookNumber, myText.Title, myText.Author, myText.Price, myText.Grade);
            }
            else 
            {
                CoffeeTableBook myCoffee = new CoffeeTableBook();
                 
                Console.WriteLine("Enter Title");
                myCoffee.Title = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Author?");
                myCoffee.Author = Convert.ToString(Console.ReadLine());
                Console.WriteLine("Enter price");
                myCoffee.Price = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("This is book {0} Titled: {1} Written by: {2} Price: {3}", myCoffee.BookNumber, myCoffee.Title, myCoffee.Author, myCoffee.Price);
            }
    }
 }   
    static class Book
    {
        public double price;
        public int BookNumber { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public virtual double Price { get; set; }
    }
    static class TextBook : Book
    {
        public override double Price {
        get { return price; }
        set { 
           if (value < 20.00 || value > 80.00)
           { 
               Console.WriteLine("Invalid price.");
           }
           else
           {
               Console.WriteLine("Valid Price");
               price = value;
           }
        }
        }
        public char Grade { get; set; }
    }
    static class CoffeeTableBook : Book
    {
        public override double Price
        {
            get{ return price; }
            set{
                if (value < 35.00 || value > 100.00)
                {
                    Console.WriteLine("invalid Price.");
                }
                else
                {
                    Console.WriteLine("Valid Price");
                    price = value;
                }
            }
        }
    }
}



What I have tried:

Over the past 5 days I've tried changing places of curley brackets, adding and deleting them in different areas as well. I think my classes, inheritance and if-else statements are right. I made almost everything public out of frustration.

And I debugged to the best of my ability.

解决方案

You can't create instances of static classes:

Book myBook = new Book();


-> Remove the static modifier from your three "book-classes".

Variables declared in methods can't have modifiers because they're automatically and always only visible within that method:

public string input;


The advice would be to remove the public modifier from that variable declaration, but: You then re-declare input here:

string input = Console.ReadLine();


-> Completely remove the first declaration of input.

TextBook.Grade is of type char, so you can't assign a string:

myText.Grade = Convert.ToString(Console.ReadLine());


-> Proposed solution:

string gradeInput = Console.ReadLine();
if (gradeInput.Length == 1)
{
   myText.Grade = gradeInput[0];
}
else
{
   // handle malformed input (e.g. error message, let user try again)
}



With these modifications all compiler errors should be dealt with.

Then there are some other issues which can be considered style/good practice issues:

- Don't validate values in property-setters. Alternatives: Either provide all values through the constructor, validate them there and in case of an invalid value, throw an exception. Or have a dedicated method for validation like:

bool IsValid()
{
   // ...
}


(Which would, in an application where those books would subsequently be stored into a database, be called before the book would be stored and in case it's invalid, the saving-process would be stopped. So, in your case it would be a bit artificial.)

- Console.ReadLine() already returns a string. So passing it into Convert.ToString(..) is completely redundant:

Convert.ToString(Console.ReadLine());



- For converting strings into other types, the preferred (static) methods are .Parse(..) or .TryParse(..) of the according types. The difference being that .Parse(..) returns the parsed value if successful and throws an exception if not successful while .TryParse(..) returns true if successful and places the parsed value into an out-parameter and returns false if not successful. The latter is often the more convenient option:

double price;
if (!Double.TryParse(Console.ReadLine(), out price))
{
   // handle malformed input (e.g. error message, let user try again)
}



A free PDF-book on programming in C#: Introduction to Programming with C# / Java Books[^]


What would you expect if you are not even trying to write in this language, C#?
And not even trying to understand very clear messages of a compiler. Apparently, you are falling in "frustration" well too early.

The trouble starts with this line:

public string input;


What do you think it possibly could mean? This is a syntax of the declaration of the member of a class, a field. But you are placing it at the level of the implementation of the method Main. Methods don't have members, only types have. Removing "public" would fix it, by turning a member declaration into a variable.

This line screws up the rest of the code. From this point, there nothing to discuss. But on some line below you have

static class TextBook : Book


What, did you fail to read that C# and .NET does not allow extension of static types? This is not a general rule of programming, but not allowed in .NET. This line screws up the whole class. And so on… I honestly explained first bug and don't need to go any further.

Fix it and proceed.

Now, I can see two possibilities: 1) you've don few random mistakes and failed to understand the compiler messages, due to low experience, 2) you have no idea of some very basic programming principles and no glue on how the language you are trying to use works. Second case seems more likely to me. Then you should start with having some manual on the language and platform, with explanation of general programming ideas, and read it all, without skipping a single line. You have to understand that you all you need is understanding; you don't have to memorize anything. But you should solve simple exercises to each chapter, better all of them, unless you feel some are too trivial. This way, most people managed to come to enlightenment, so you can, too.

I would add my simple rule: don't write a single line of code which you don't understand.

—SA


这篇关于Newb继承受挫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆