c# - 我需要帮助从单个方法和类实例化多个对象

标签 c# instantiation

C# 家庭作业问题:我正在创建一个控制台应用程序,它提示输入两个整数、提示执行哪个数学运算并返回结果。我能够让它与我的两个硬编码操作数一起工作,现在我试图通过用户输入而不是硬编码变量来实例化两个单独的对象。我已经将它简化为我遇到问题的准系统代码,我怀疑这个问题与我从同一方法创建两个对象的方式有关......但我不确定是什么.

这是我的主课...

 public class MainModule 
 {
    public static void Main(string[] args)
    {
         // get Operands
        Console.WriteLine("You Will Be Entering Two Integers.\n");
         //
        MathUI myOperand1 = new MathUI();
        int op1 = myOperand1.EnterInteger();
         //
        MathUI myOperand2 = new MathUI();
        int op2 = myOperand2.EnterInteger();

        Console.WriteLine("You chose {0} and {1}.", (int)op1, (int)op2);
        Console.ReadLine();
    }
 }

...以及接受输入的 MathUI 类。

public class MathUI
{
    public int EnterInteger()
    {
        Console.Write("Enter an integer: ");
        int enteredInteger = Console.Read();
        return (enteredInteger);
    }
}

当我执行程序时,我得到一个输入整数的提示。例如,我输入 3,这是我的输出。

You Will Be Entering Two Integers.

Enter an integer: 3
Enter an integer: You chose 51 and 13.

Math demo completed
Press <enter> to quit

当我输入第一个整​​数后按回车键时,我会自动得到第二个整数;当我尝试输出整数值时,它们与我的输入不匹配。

这是怎么回事?我实例化 MathUI 和我的两个操作数的方式有问题吗?我是否只需要实例化 MathUI 的一个实例,然后在该实例下声明两个变量?我也不确定为什么整数输出与我的输入不匹配。所有变量都转换为 int,所以我应该一直使用 int,对吧?我尝试将它们转换为整数——(int)op1——以防万一 op1 以某种内部形式保存……但不知道那里发生了什么.

我错过了什么?

最佳答案

您需要将 Console.Read 设为 Console.ReadLine,因为 readline 由返回键触发。

public class MathUI
{
    public int EnterInteger()
    {
        Console.Write("Enter an integer: ");
        int enteredInteger = Convert.ToInt32(Console.ReadLine());
        return (enteredInteger);
    }
}

关于c# - 我需要帮助从单个方法和类实例化多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15592606/

相关文章:

c# - 加载一部分 XML

c# - 如何对 MVC ASP.Net 返回正确的 View 进行单元测试?

c++ - 强制模板成员函数实例化

c# - .Net 应用程序使用的文件放在哪里

c# - 如何在运行时制作一个使用 GetType ("Class Name") 获得的类型的列表<>?

c# - Java 到 C# : HashMap, 映射和队列

c++ - 实例化多个类型的成员函数模板

java - 内部类的实例化

c++ - 使用类方法而不实例化的优点/缺点

Android SensorEventListener 语法