我是C#的新手,并试图制作一个音量校准,允许您选择想要找到我试图用读取线做的音量的形状。我得到的不能转换类型'字符串'到' AreaCal.VolumeSphere'在静态void main中的读取行
using System;
namespace AreaCal
{
class VolumeSphere
{
double pi = 3.14159265359;
double ft = 1.333333333333333333333333333333333333;
double r;
public void Details()
{
Console.WriteLine("Volume of a Circle");
Console.WriteLine ("Type Radius");
r = Convert.ToInt32 (Console.ReadLine ());
}
public double GetVolume()
{
return ft * pi * r * r * r;
}
public void Display()
{
Console.WriteLine ("Volume: {0}", GetVolume());
}
}
class MainClass
{
public static void Main (string[] args)
{
VolumeSphere Sphere = new VolumeSphere ();
Sphere = (Console.ReadLine ());
if (Sphere != null)
Console.WriteLine ("awwww");
}
}
}
答案 0 :(得分:0)
Sphere
是类VolumeSphere
的对象,但您在此处指定字符串Console.ReadLine
是错误的。可能你想做类似的事情:
VolumeSphere Sphere = new VolumeSphere();
Sphere.Details();
Sphere.Display();
但你的要求并不清楚。所以请提供更多细节。并且还考虑使用构造函数将半径值传递给VolumeSphere
类。
答案 1 :(得分:0)
VolumeSphere Sphere = new VolumeSphere();
Sphere = (Console.ReadLine ());
这是抛出错误。 Console.Readline()返回从标准输入读入的字符串。您正在尝试将此分配给变量Sphere,您声明它是VolumeSphere类型。我不确定你从标准输入读取什么,但我认为它是半径。
你需要这样做;
string radius = Console.ReadLine();
VolumeSphere Sphere = new VolumeSphere(Convert.ToDouble(radius));
这将转换为double的字符串参数传递给VolumeSphere构造函数,您将在类VolumeSphere中定义它:
public VolumeSphere(double r)
{
this.r = r;
}
在读取输入之前,您还应该删除Details方法并将其writelines放在main中,因为最好封装模型和用户界面。
答案 2 :(得分:0)
在阅读您的问题时,您提到您正在尝试选择多个计算器,在您的示例中,您尝试将键盘输入分配给VolumeSphere对象。这是一个快速而肮脏的计算器菜单实现,您可以使用它并扩展它以满足您的需求。
class MainClass
{
static void Main(string[] args)
{
int value;
bool run;
run = true;
while(run)
{
Console.WriteLine("Calculator Menu");
Console.WriteLine("1: Compute Volume of a Sphere");
Console.WriteLine("2: Compute Something else");
Console.WriteLine("etc,etc,etc");
if (int.TryParse(Console.ReadLine(), out value))
{
switch (value)
{
case 1:
VolumeSphere Sphere = new VolumeSphere();
Sphere.Details();
Console.WriteLine(Sphere.GetVolume());
Sphere.Display();
break;
case 2:
break;
case 3:
break;
default:
Console.WriteLine("GoodBye");
run = false;
break;
}
}
}
Console.WriteLine("Press Any Key to Exit");
Console.ReadLine();
}
}