【问题标题】:Java homework help, using constructors and methods [closed]Java作业帮助,使用构造函数和方法[关闭]
【发布时间】:2013-12-02 02:01:10
【问题描述】:

有人可以向我解释以下问题吗?我不是要你为我回答,而是要你向我解释,这样我才能朝着正确的方向前进。我一直在这门课上苦苦挣扎……我自学了html和css,可以像手背一样流利地写出来。所以当我报名参加这门课时,我想我也会很容易地学习 java... 伙计,我错了:)

public class TestGlass 
{ 
    public static void main(String [] args) 
    { 
        Glass milk = new Glass(15); // 15 ounces of milk 
        Glass juice = new Glass(3); // 3 ources of juice 

        milk.drink(2); 
        milk.drink(1); 

        milk.report(); 

        juice.fill(6);  // went from 3 to 9 ounces 
        juice.drink(1); // now down to 8 ounces 

        juice.report();  

        juice.spill(); 

        juice.report(); 
   } 
} 

class Glass 
{ 
   // Declare a variable to keep track of the number of ounces in a glass here 


   // Write the methods here.  You will need a constructor, plus the drink, report, fill, 
   // and spill methods.  These methods are for any generic glass -- they are not specific  
   // to the milk or juice instances of a glass (i.e., you should not mention "juice" or  
   // "milk" inside the Glass class). 

} 

这就是输出的样子......

玻璃有 12 盎司。
玻璃杯有 8 盎司。
玻璃有 0 盎司。

【问题讨论】:

  • 您究竟需要澄清什么?
  • 几乎任何基本的 Java 教程都会向您展示构造函数和方法的示例。我建议你使用谷歌。

标签: java methods constructor


【解决方案1】:

看看教授帮助你插入的评论块:

// Declare a variable to keep track of the number of ounces in a glass here 


// Write the methods here.  You will need a constructor, plus the drink, report, fill, 
// and spill methods.  These methods are for any generic glass -- they are not specific  
// to the milk or juice instances of a glass (i.e., you should not mention "juice" or  
// "milk" inside the Glass class). 

看起来你应该:

  • 声明一个变量以在课程开始时跟踪玻璃杯中的盎司数。
  • 写一个:

    • 构造函数采用一个参数表示盎司数。
    • drink 方法从盎司数中减去传递给该方法的盎司数。
    • fill 方法将传递的盎司数与盎司数相加。
    • spill 方法将盎司数设置为 0,因为它都溢出了。
    • report 打印方法:

      Glass has <number of ounces> ounces.
      

      其中&lt;number of ounces&gt; 是变量中的盎司数。

之后,你就完成了。

【讨论】:

  • 他可以补充一个有趣的奖励:如果您尝试喝的水超过玻璃杯中的水量,则抛出异常!
  • @Sam_D 如果 OP 只是赶上 java,也许他不应该。
【解决方案2】:

您应该编写 Glass 类的构造函数和方法,以便测试编译、运行并产生预期的输出。这是测试驱动开发的一个例子——首先编写测试,然后是测试对象的实现。

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多