I am to create a program in Java using multiple methods inside the driver class. Previously, we have only used the main method in such applications.
I know I am to use something like this:
public static void main(String[] args)
{
U4A4 u = new U4A4();
u.run();
}
to run the method public U4A4().
Yes, I know this is terribly basic, but I've been searching around all evening and I thought someone here might be able to put it in simple terms how exactly I should do this.
My compiler is getting mad when I try to put in public class U4A4 implements Runnable at the top of my code (it's right after my imports) and starts wanting me to make it abstract. I have no idea what that is.
So, where do I put implements Runnable and where do I use run()?
Thank you so much for bearing with me here.
Edit: This is what I've got so far. http://pastebin.com/J8jzzBvQ
You have implemented Runnable interface, but not overriden the run method of that interface. I have commented code where you will have to place your thread logic so the thread will work for you.
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.
}
}
Related
I was tasked to create a program that would calculate how fast you must go to reach a certain distance (miles per hour) at a certain time (in hours). You are supposed to consider a 5 minute break for every 100 miles. Also, the program has to be written using 4 methods and a main method. I already did a majority of the program but I don't know how to properly output my results. I am positive that I am doing something wrong with one of the methods but I don't know how to fix it. Heres what I have:
import java.util.Scanner;
public class I95Machine {
public static void userMessage() {
System.out.println("Welcome to I95 Speed Machine");
System.out.println("You will have to supply:\n+ The distance you want to travel, in miles\n+ The time you have available, in hours");
}
public static double computeTravelSpeedOne(double inputDist, double inputTime) {
double stopTime, travelSpeed;
int timeQuotient;
timeQuotient = (int) (inputDist / 100);
stopTime = timeQuotient * 5;
if ((timeQuotient % 100) > 0) {
stopTime += 5;
}
stopTime /= 60;
inputTime = inputTime - stopTime;
travelSpeed = inputDist / inputTime;
if (inputTime > 0) {
return travelSpeed;
} else {
return 0.0;
}
}
public static double inputDistAndTime() {
Scanner keyboard = new Scanner(System.in);
double distNum = 0, timeNum = 0, distance, time;
System.out.print("Enter distance to travel : ");
distNum = keyboard.nextDouble();
distance = distNum;
System.out.print("Enter time available : ");
timeNum = keyboard.nextDouble();
time = timeNum;
return computeTravelSpeedOne(distance, time);
}
public static void displayOutput(double travelSpeed) {
boolean speedLim = computeTravelSpeedOne() > 65;
System.out.print("You will have to travel at ");
System.out.println(computeTravelSpeedOne() + " MPH");
System.out.print("Over the speed limit : ");
System.out.print(speedLim);
}
public static void main(String[] args) {
userMessage();
inputDistAndTime();
displayOutput();
}
}
Not sure if I understand your question, but in displayOutput you call computeTravelSpeedOne without any arguments, this might fail...
I have been working on these programs.
They don't have any errors but I need to make them return a result in order for them to work properly. More specifically to add a method that returns a result.
The instructions were the following:
Write a program that is split in to methods at least one of which returns a result
This is the first program:
import java.util.Scanner; // Needed to make Scanner available
public class onlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
This is the second program:
import java.util.Scanner; // Needed to make Scanner available
public class BodyAge {
public static void main(String[] args) {
CalculateAge();
} // END of main method
// Inserting age and heart rate and stretch distance
//and calculates the body age based on conditions
public static void CalculateAge() {
int age;
int heartRate;
int stretch;
Scanner input = new Scanner(System.in);
System.out.print("What is your age? ");
age = input.nextInt();
System.out.print("What is your heart rate? ");
heartRate = input.nextInt();
if (heartRate <= 62) {
age -= 5; // block of code to be executed if condition1 is true
} else if (62 <= heartRate && heartRate <= 64) {
age--; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (65 <= heartRate && heartRate <= 70) {
age++; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age += 2; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.print("How far can you stretch? ");
stretch = input.nextInt();
if (stretch <= 20) {
age += 4; // block of code to be executed if condition1 is true
} else if (20 <= stretch && stretch <= 32) {
age++; // block of code to be executed if the condition1 is false and condition2 is
// true
} else if (33 <= stretch && stretch <= 37) {
age = age + 0; // block of code to be executed if the condition1 and condition2 are false and
// condition3 is true
} else {
age = age + 3; // block of code to be executed if the condition1 and condition2 and condition3
// are false and condition4 is true
}
System.out.println("Your body's age is " + age);
} //END of CalculateAge
}
Here's an example of one possible way you might consider breaking up a class into using some methods with returns. Let's take your first class for this example. You frequently are taking input from your user.
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
This could potentially be broken out into another method for condensed reusability.
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
From there you can replace your calls for information with this method. Full example:
import java.util.Scanner; // Needed to make Scanner available
public class OnlineCalculator {
public static void main(String[] args) {
calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
public static void calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
a = askForInt(scanner, "Amount of loan at start of year? ");
b = askForInt(scanner, "Amount paid off this year? ");
scanner.close();
int c;
c= a - b;
double d;
final double e;
d = c * 1.07 * 10.0;
e = (int)d / 10.0;
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
public static int askForInt(Scanner scanner, String message) {
System.out.print(message);
return scanner.nextInt();
}
}
First program,
You could for example split your calculate() method into 2 method and move your int variable "a" and "b" in the main() method
1ST method:
void getInput(){
...
}
2nd method:
int calculateAndreturnResult(int a, int b) {
...
}
Finally use those method in the main() and print the result :
getInput();
int result = calculateAndreturnResult(){
}
system.out.println(result);
So how Java will work is the compiler will only read commands from the "main" method. So in the case of the calculator, Java will see that you want to run the calculator method, which has a return type of "void" It goes PUBLIC (meaning other classes can see and interact with it) STATIC (basically meaning that the method belongs to the class itself, not instances of the class) VOID ( this is your return type, meaning after the method is done, what is being put back into main) so if you want a method to return something, you need to change the return type. In the case of your calculator project something like this would split it up into 2 methods one of which returns something:
public class OnlineCalculator {
public static void main(String[] args) {
Calculator();
} //END of main method
// Inserting your loan at the start of the year and the amount paid off
// and calculates the amount yet to pay with interest
//
//this will return an int type
public static int loanDifference(int amountOwed, int amountPaid) {
int c = amountOwed - amountPaid;
return c;
}
// this will return a double type
public static double newAmountOwed(double d) {
double e = (int)d / 10.0;
return e;
}
public static void Calculator(){
int a;
int b;
Scanner scanner = new Scanner(System.in);
System.out.print("Amount of loan at start of year? ");
a = scanner.nextInt();
System.out.print("Amount paid off this year? ");
b = scanner.nextInt();
scanner.close();
int c = loanDifference (a, b);
double d;
d = c * 1.07 * 10.0;
final double e = newAmountOwed(d);
System.out.println("The new amount owed is (in pounds): " + e);
} //END of Calculator
}
seems like they want you to put more code in, but the idea is that they want you to know how to use methods that work together to make something at the end!
use the same idea with the other one!
I'm sure this has a simple solution, but I'm new to Java and can't work it out.
I have a subclass Payroll that extends a superclass Pay, it contains an overridden method called 'calc_payroll'. From this method, I want to call the superclass method of the same name, and assign the output to a variable in the overriding method. My code is below
public class Payroll extends Pay
{
public double calc_Payroll()
{
double grossPay = super.calc_Payroll();
double taxAmt = tax(grossPay);
double netPay = grossPay - taxAmt;
System.out.println(grossPay);
return netPay;
}
}
Below is the code from the calc_payroll method in the superclass
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
the superclass method functions without issue to calculate and return the gross pay when called from a different subclass, but when calling it from a method with the same name, the print line in the code above (that I have labelled for testing) displays zero's for all variables
Code for full 'Pay' class is below as requested
public class Pay
{
private double ttlHours;
private int stHours;
private double rate;
double grossPay = 0.0;
final double TAXL = 0.07;
final double TAXM = 0.1;
final double TAXH = 0.16;
public void SetHours(double a)
{
ttlHours = a;
}
public void SetHoursStr(int a)
{
stHours = a;
}
public void SetRate(double a)
{
rate = a;
}
public double GetHours()
{
return ttlHours;
}
public int GetStHours()
{
return stHours;
}
public double GetRate()
{
return rate;
}
public double taxRate()
{
double taxRate = 0.0;
if(grossPay <= 399.99)
{
taxRate = TAXL;
}
else if(grossPay <= 899.99)
{
taxRate = TAXM;
}
else
{
taxRate = TAXH;
}
return taxRate;
}
public double tax(double grossPay)
{
double ttlTax = 0.0;
if(grossPay < 400.00)
{
ttlTax += (grossPay * TAXL);
}
else if(grossPay < 900.00)
{
ttlTax += (grossPay * TAXM);
}
else
{
ttlTax += (grossPay * TAXH);
}
return ttlTax;
}
public double calc_Payroll()
{
double otRate = rate * 1.77;
double otHours = ttlHours - stHours;
if(stHours == 0)
{
grossPay = otHours * rate;
}
else
{
grossPay = ((stHours * rate) + (otHours * otRate));
}
System.out.println(stHours + "//" + otHours + "//" + rate);//for testing
return grossPay;
}
}
The subclass Payroll contains no other code
Below is the code that accepts user input to assign values to the initialized variables
public class CalPayroll extends Pay
{
Payroll nPay = new Payroll();
Accept Read = new Accept();
public void AcceptPay()
{
char select = '0';
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
}
public void displayInfo()
{
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
System.out.println("Gross pay is :" + currency.format(calc_Payroll()));
System.out.println("Tax is :" + percent.format(taxRate()));
System.out.println("Net pay is :" + currency.format(nPay.calc_Payroll()));
Screen.ScrollScreen(1);
}
}
I'm confused!
Its clear from you code that ttlHours, stHours and rate are not initialised with some reasonable value. So when you just call super.calc_Payroll(), values like 0 or 0.0 are used as i explained in my comment. Its good to first set values of these variables before calling super.calc_Payroll().
SetHours(23.4); //some value
SetHoursStr(5); //some value
SetRate(2.3); //some value
Also you don't have constructor for Pay class, try making it and initialising all uninitialised variable in constructor or use setter/getter methods to set and get values.
Since your both classes extends Pay class, it creates the problem which you are facing. When you call SetHours(Read.AcceptInputDouble()), it set the variable inherited by CalPayroll from Pay, not the variables inherited by Payroll class. What you have to do is to set variables for Payroll instance as well as for current class as both extends Pay. Do the following replace your while loop as,
while(select != 'e' && select != 'E')
{
System.out.println("Payroll Computation \n");
System.out.print("Enter number of hours worked (00.0) <0 for Quick exit>: ");
SetHours(Read.AcceptInputDouble());
nPay.SetHours(GetHours());
System.out.print("Enter first number of hours straight (integer or 0 to disable): ");
SetHoursStr(Read.AcceptInputInt());
nPay.SetHoursStr(GetStHours());
System.out.print("Enter hourly rate of worker (00.00): ");
SetRate(Read.AcceptInputDouble());
nPay.SetRate(GetRate());
Screen.ScrollScreen('=', 66, 1);
Screen.ScrollScreen(1);
displayInfo();
System.out.println("e to exit, any other letter + <Enter> to continue");
select = Read.AcceptInputChar();
}
Please post the complete code.
It seems that for some reason your variables of super class method not getting assigned values properly. And they are initialized with their default values which is making everything 0. I'll be able to help better if you paste the complete class.
I did this once before on a different project, but I have no idea how to do it on this project. I just need to do the calculations for my output in a separate method and then have them print to the console from the main method. I know that this is probably really easy for most of you but I just started coding yesterday, so I have never learned this.
My code:
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
private static double doyourstuff(double d1,double d2,double d3)
{
write your entire logic here as above written in main method.
return calculated_balance;
}
public static void main(String[]args)
{
--read values via scanner as you read above.
double S= doyourstuff(d1,d2,d3);
System.out.println("Your balance in that time span is " + S + ".");-- your final call
}
Currently I am writing a program for an introductory Java class. I have two pieces to my puzzle. Hopefully this is a relatively simple to answer question.
Firstly, here is what I am trying to use as my main program:
import java.util.Scanner;
public class TheATMGame
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double newBalance = 0;
double monthlyInterest = 0;
int answer = 0;
int i=1;
while (i < 100) {
System.out.print ("Please enter your ID: ");
answer = input.nextInt();
System.out.println(" ");
if (answer >=0 && answer<10)
TheATMGame.runGame (answer);
else
System.out.println("Sorry, this ID is invalid.");
}
}
public static void runGame(int id) {
double amount = 0;
int continueOn = 0;
while (continueOn < 4) {
ATMGame myATM = new ATMGame();
Scanner input = new Scanner(System.in);
System.out.println ("---Main menu--- ");
System.out.println ("1: Check balance ");
System.out.println ("2: Withdraw ");
System.out.println ("3: Deposit ");
System.out.println ("4: exit ");
int answer = input.nextInt();
if (answer == 1)
System.out.println("your balance is: " + myATM.getBalance (id));
else if (answer == 2){
System.out.println("Enter an amount to withdraw: ");
amount = input.nextInt();
myATM.withdraw(amount, id);
}
else if (answer == 3)
{
System.out.println("Enter an amount to deposit: ");
amount = input.nextInt();
myATM.deposit(amount, id);
}
else if (answer == 4)
continueOn = 4;
else if (answer > 4)
System.out.println ("Please review the main menu. " +
"Your selection must be between 1-4.");
}
}
//ATM class (balance, annualInterestRate2, id2)
//ATM myATM = new ATM (20000, 4.5, 1122 );
//newBalance = myATM.withdraw(2500);
//newBalance = myATM.deposit(3000);
//monthlyInterest = myATM.getMonthlyInterestRate();
//System.out.println("Your current balance is: " + newBalance);
//System.out.println ("Your monthly interest rate is: " + monthlyInterest);
}
Now here are all of the classes I want to impliment into that program:
import java.util.Date;
public class ATMGame {
private double annualInterestRate = 0;
private double balance = 0;
private int id = 11;
private int[] ids = {0,1,2,3,4,5,6,7,8,9};
private int[] balances = {100,100,100,100,100,100,100,100,100,100};
public Date dateCreated;
public ATMGame() {
}
public ATMGame (double balance2, double annualInterestRate2, int id2) {
balance = balance2;
annualInterestRate = annualInterestRate2;
id = id2;
dateCreated.getTime();
}
public double getMonthlyInterestRate() {
double monthlyInterest = annualInterestRate/12;
return monthlyInterest;
}
public double withdraw(double amountWithdrawn, int id) { //This method withdraws money from the account
double newBalance = balances[id] - amountWithdrawn;
System.out.println("Your withdrawel has processed. New balance: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double deposit(double amountDeposited, int id) { //This method deposits money in the account
double newBalance = balances[id] + amountDeposited;
System.out.println("Your deposit has processed. New Balance is: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double getBalance(int id) {
double myBalance = balances[id];
balance = myBalance;
return myBalance ;
}
}
When I try to run the first program it says "No Main classes found."
As you can see I have written the line " public void Main() ..." to take care of this, but eveidently it does not work. What am I doing wrong?
Replacing "public void Main() {" with "public static void main(String[] args) {" still returns the error: "No Main classes found." :/
http://img21.imageshack.us/img21/9016/asdfsdfasdfg.jpg
I was able to fix it by changing Main.java to TheATMGame.java and then running from ATMGame.java.
You should use:
public static void main(String[] args)
Instead of Main because the JVM calls this method first. It is a convention.
You've just misdefined main. Should be:
public static void main(String[] args) {
....
}
You're going to run into some other problems with your code, though. From a quick glance...
Your main() is a function, as well as runGame() - one shouldn't be defined within the other.
You cannot name your two classes the same thing - call the main() class something different than ATMGame.
Not sure where you're going with ATM class (balance, annualInterestRate2, id2), but it's not valid Java.
Your method signature must be:
public static void main(String[] args) {
...
}
That's the convention you have to follow. Anything else won't work.
In your class ATMGame, replace the following:
public void Main() {
with:
public static void main(String[] args) {
Additionally, since this method has to be static, you'll need to change the following:
if (answer >=0 && answer<10)
runGame (answer);
else
with:
if (answer >=0 && answer<10)
ATMGame.runGame (answer);
else
Then finally, you need to change the method signature of rungame to also be static. Change it from:
public void runGame(int id) {
to:
public static void runGame(int id) {
The names of your public classes should match the file names. This is not the case in your screenshot. Also make sure that everything compiles correctly and then retry (using a public static void main(String[] args) { ... } method).