我将使用驱动程序类中的多种方法在 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
最佳答案
您已经实现了 Runnable 接口(interface),但没有重写该接口(interface)的 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.
}
}
关于Java 驱动程序类、Runnable 和 main 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13409824/