【问题标题】:Java driver class, Runnable, and main methodJava驱动类、Runnable和main方法
【发布时间】:2012-11-04 18:41:50
【问题描述】:

我将使用驱动程序类中的多种方法在 Java 中创建一个程序。以前,我们只在此类应用中使用过 main 方法。

我知道我要使用这样的东西:

public static void main(String[] args)
{
    U4A4 u = new U4A4();
    u.run();
}

运行方法public U4A4()

是的,我知道这是非常基本的,但我整个晚上都在寻找,我想这里有人可能能够简单地说我应该如何做到这一点。

当我尝试将public class U4A4 implements Runnable 放在我的代码顶部(就在我的导入之后)并开始希望我将其抽象化时,我的编译器变得疯狂。我不知道那是什么。

那么,implements Runnable 应该放在哪里,run() 应该放在哪里?

非常感谢您在这里与我相处。

编辑:这是我到目前为止所得到的。 http://pastebin.com/J8jzzBvQ

【问题讨论】:

  • 请写完整的类代码
  • 这是我到目前为止所得到的。 pastebin.com/J8jzzBvQ
  • 您已将implents Runnable 放在正确的位置,并在正确的位置使用run。仔细阅读错误消息,因为编译器已经告诉你为什么U4A4 是抽象的。
  • u4a4.U4A4 不是抽象的,不会覆盖 java.lang.Runnable 中的抽象方法 run() 公共类 U4A4 实现 Runnable // 我不知道这是什么意思。
  • Runnable 通常用于您希望应用程序是多线程的。这似乎不是您所需要的,那么您为什么要实施Runnable?您可以在程序中使用多种方法,而无需使用Runnable

标签: java methods driver main runnable


【解决方案1】:

您已经实现了Runnable 接口,但没有覆盖该接口的run 方法。我已经注释了代码,您必须在其中放置线程逻辑,以便线程为您工作。

import java.util.Scanner;

public class U4A4 implements Runnable
{
    private int count = 0;
    private double accum = 0;
    private int apr, min, months;
    private double balance, profit;

    public static void main(String[] args)
    {
        U4A4 u = new U4A4();
        u.run();
    }

    public U4A4()
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter credit card balance: ");
        balance = in.nextDouble();
        System.out.print("\n\nEnter minimum payment (as % of balance): ");
        min = in.nextInt();
        System.out.print("\n\nEnter annual percentage rate: ");
        apr = in.nextInt();

        profit = this.getMonths(balance);

        System.out.println("\n\n\n# of months to pay off debt =  " + count);
        System.out.println("\nProfit for credit card company = " + profit + "\n");
    }

    public double getMonths(double bal)
    {
        double newBal, payment;
        count++;

        payment = bal * min;

        if (payment < 20 && bal > 20)
        {
            newBal = bal * (1 + apr / 12 - 20);
            accum += 20;

        } else if (payment < 20 && bal < 20)
        {
            newBal = 0;
            accum += bal;
        } else
        {
            newBal = bal * (1 + apr / 12) - payment;
            accum += payment;
        }
        if (newBal != 0) {
            getMonths(newBal);
        }

        return accum;
    }

    public void run() {
        // TODO Auto-generated method stub
        // You have to override the run method and implement main login of your thread here.
    }
}

【讨论】:

  • 非常感谢!在摆弄之后,我想我只是在逻辑上有一些错误,然后我就会被设置。
  • 如果我想访问 getMonths() 方法,我应该怎么做?
猜你喜欢
  • 1970-01-01
  • 2018-03-29
  • 2014-04-21
  • 1970-01-01
  • 2016-07-29
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多