I'd appreciate it if anyone could help. Just what seems like a novice question but I can't figure it out.
I have 3 classes Class1, Class2, UseClass.
In Class1 I have a get/set method (COST is used elsewhere in Class1 but not in those methods)
int class1Num;
final double COST = 120;
public int getNum()
{
return class1Num;
}
public void setNum(int newNum)
{
class1Num = newNum;
}
In Class2 I have a final variable and a normal variable and another get/set method.
Class2 extends Class1.
final double FINALNUM = 50;
double totalNum;
public double getTotalNum()
{
return totalNum;
}
public void setTotalNum(int class1Num)
{
totalNum = COST * getNum() + FINALNUM;
}
public void display()
{
System.out.println("Final Number: " + getTotalNum() );
}
Basically what I need to do is I need to in Class2. First multiply COST by the getNum() method from Class1 and then add FINALNUM to that total. This is just my recent attempt but I've tried adding FINALNUM in the system.out to no avail (although multiplication works fine for some reason).
display() is called in the UseClass to output the final result.
I have no other ideas and not exactly sure what I'm looking for when searching online so I figured asking here may help
Any help would be great
Thanks.
According to your statements, the classes are following I guess:
public class Class1 {
int class1Num;
final double COST = 120;
public int getNum()
{
return class1Num;
}
public void setNum(int newNum)
{
class1Num = newNum;
}
}
public class Class2 extends Class1{
final double FINALNUM = 50;
double totalNum;
public double getTotalNum()
{
return totalNum;
}
public void setTotalNum(int class1Num)
{
// Note: need assign field member "class1Num" inherited from Class1.
// Otherwise, it will be zero and cause incorrect value of getNum()
totalNum = COST * getNum() + FINALNUM;
}
public void display()
{
System.out.println("Final Number: " + getTotalNum() );
}
}
The problem is that "setTotalNum(int class1Num)" doesn't assign class1Num which inherited from Class1. You can call "setNum(class1Num);" before" totalNum = COST * getNum() + FINALNUM;"
public class Class2 {
...
public void setTotalNum(int class1Num) {
setNum(class1Num);
totalNum = COST * getNum() + FINALNUM;
}
....
}
I'm struggling with one of the final parts of a school assignment.
I had asked this question on another question I had but did not receive an answer.
I have two methods in my super class that I need to use in my sub class and the one method must be invoked inside of the other to return a result, I'm stumped on how to do this.
public class Pay
{
private float hours;
private float rate;
private int hrsStr;
float gross;
double tax;
public void calc_Payroll()
{
if (hrsStr != 0)
gross = hrsStr + ((hours - hrsStr) * 1.33f) * rate;
else
gross = hours * rate;
}
public void tax(double a)
{
if (gross <= 399.99)
tax = .92;
else
if (gross <= 899.99)
tax = .88;
else
tax = .84;
}
public void setHours(float a)
{
hours = a;
}
public float getHours()
{
return hours;
}
public void setRate(float a)
{
rate = a;
}
public float getRate()
{
return rate;
}
public void setHrsStr(int a)
{
hrsStr = a;
}
public int getHrsStr()
{
return hrsStr;
}
}
That is the entire superclass and i need to call the calc_Payroll() method and the tax() method to the subclass, well I need tax() to be inside calc_Payroll() because I need to calculate the net pay from those two methods.
public class Payroll extends Pay
{
float net;
#Override
public void calc_Payroll()
{
//I need to calculate the the net pay here.
}
}
Are you struggling with the syntax of Java?
public class Payroll extends Pay
{
float net;
#Override
public void calc_Payroll()
{
// you can call `super.calc_Payroll()`
// you can call `tax(double a)`
}
}
I am having a rather trivial problem creating my own exception class. I have extending it and am trying to recieve a double in the constructor but I keep getting errors.
Error inside of bankaccount #withdraw "incompatible types: InsufficientFundsException cannot be converted to throwable"
Exception class:
public class InsufficientFundsException extends RuntimeException {
private double shortFall;
public InsufficientFundsException(double a) {
super("Insufficient funds");
shortFall = a;
}
public double getAmount() { return shortFall; }
}
Bank Account class:
public class BankAccount {
private int accountNumber;
private double balance;
// Class constructor
public BankAccount(int account) {
accountNumber = account;
balance = 0.0;
}
public int getAccountNumber() {
return accountNumber;
}
public double getBalance()
{
return balance;
}
public void deposit(double b) {
balance += b;
}
public void withdraw(double w) throws InsufficientFundsException {
double difference;
if(w > balance) {
difference = w - balance;
} else {
balance -= w;
}
}
I would like to withdraw money unless the withdraw is greater than the current balance. In which case I want to throw an exception. I also tried to throw and exception inside of the if but I get:
constructor InsufficientFundsException in class InsufficientFundsException cannot be applied to gived types;
required: no arguments
found: double
reason: actual and formal argument lists differ in length
public void withdraw(double w) {
double difference;
if(w > balance) {
difference = w - balance;
Exception ex = new InsufficientFundsException(difference);
} else {
balance -= w;
}
}
I only have the one constructor though. Any advice or help is appreciated.
Have you tried...
throw new InsufficientFundsException(difference);
in place of
Exception ex = new InsufficientFundsException(difference);
That's generally how exceptions are thrown.
Updated code snippet...
public void withdraw(double w) throws InsufficientFundsException {
double difference;
if(w > balance) {
difference = w - balance;
throw new InsufficientFundsException(difference);
} else {
balance -= w;
}
}
Ran with...
public static void main(String[] args){
BankAccount account = new BankAccount(1);
account.withdraw(5.0);
}
Got....
Exception in thread "main" com.misc.help.InsufficientFundsException: Insufficient funds
at com.misc.help.BankAccount.withdraw(BankAccount.java:32)
at com.misc.help.BankAccount.main(BankAccount.java:40)
I am trying to call my object via the main function. Since it needs static reference , but I somehow can't get to do it. Can someone please tell me what am I doing wrong?
private double checking;
private double saving;
public BankDisplay(double checking,double saving) // Constructor for subclass
{
checking=1000;
saving=1000;
}
public void setChecking(double checking){
this.checking=checking;
}
public double getChecking(){
return checking;
}
public void setSaving(double saving){
this.saving= saving;
}
public double getSaving(){
return saving;
}
BankDisplay checking1=new BankDisplay(checking, saving);
BankDisplay savings1= new BankDisplay(checking,saving);
When I am trying to print the object checking1 and saving1 in main it is showing "cant have a non static reference for a static function".
public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking=checking;
this.saving=saving;
}
There is an error in constructor.
public static void main(String[] args){
BankingDisplay d1 = new BankingDisplay(100.15,200.15);
System.out.println(d1.getChecking());
}
Your constructor's method is wrong, it should be:
public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking = checking;
this.saving = saving;
}
You also should have a toString() function in your class for you to appropriately print objects.
Such as:
public String toString() {
return String.format("Checking: %s\nSavings: %s\n", this.checking, this.saving);
}
Use like this:
System.out.println(checking1.toString());
public class BankDisplay {
private double checking;
private double saving;
public BankDisplay(double checking,double saving) // Constructor for subclass
{
this.checking= checking;
this.saving= saving;
}
public void setChecking(double checking){
this.checking=checking;
}
public double getChecking(){
return checking;
}
public void setSaving(double saving){
this.saving= saving;
}
public double getSaving(){
return saving;
}
}
public class Main {
public static void main(String[]args){
BankDisplay account1 = new BankDisplay(1000,100);
System.out.println(account1.getChecking());
}
}
This should fix your issue :D you needed this in your constructor because you were setting the constructors values, not your private variables.
This question already has answers here:
"Main method not found" error when starting program? [duplicate]
(7 answers)
Closed 5 years ago.
I need help with the main method, I'm getting this error:
Error: Main method not found in class Calculate, please define the main method as:
public static void main(String[] args)
Here's the code:
class Calculate {
private double fn;
private double sn;
private char op;
public void setNumber(double fnum, double snum){
this.fn = fnum;
this.sn = snum;
}
public double getNumber1(){
return fn;
}
public double getNumber2(){
return sn;
}
public void setOper(char oper){
this.op = oper;
}
public char getOper(){
return op;
}
public void getAnswer(){
double ans;
switch (getOper()){
case 'a': {
ans = add(getNumber1(), getNumber2());
ansOutput(ans);
break;
}case 'b': {
ans = sub (getNumber1(), getNumber2());
ansOutput(ans);
break;
}case 'c': {
ans = mul (getNumber1(), getNumber2());
ansOutput(ans);
break;
}case 'd': {
ans = div (getNumber1(), getNumber2());
ansOutput(ans);
break;
}default:
System.out.println("--------------------------");
System.out.println("Invalid choice of operator");
System.out.println("--------------------------");
}
}
public static double add(double x,double y){
return x + y;
}
public static double sub(double x, double y){
return x - y;
}
public static double mul(double x, double y){
return x * y;
}
public static double div(double x, double y){
return x / y;
}
public static void ansOutput(double x){
System.out.println("----------- -------");
System.out.printf("the answer is %.2f\n", x);
System.out.println("-------------------");
}
}
Restart your IDE and everything will be fine
From the docs
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
As you say:
error: missing method body, or declare abstract public static void main(String[] args); ^ this is what i got after i added it after the class name
You probably haven't declared main with a body (as ';" would suggest in your error).
You need to have main method with a body, which means you need to add { and }:
public static void main(String[] args) {
}
Add it inside your class definition.
Although sometimes error messages are not very clear, most of the time they contain enough information to point to the issue. Worst case, you can search internet for the error message. Also, documentation can be really helpful.
My suggestions :
Keep the program modular. Keep the Calculate class in a separate Calculate.java file and create a new class that calls the main method. This would make the code readable.
For setting the values in the number, use constructors. Do not use like the methods you have used above like :
public void setNumber(double fnum, double snum){
this.fn = fnum;
this.sn = snum;
}
Constructors exists to initialize the objects.This is their job and they are pretty good at it.
Getters for members of Calculate class seem in place. But setters are not. Getters and setters serves as one important block in the bridge of efficient programming with java. Put setters for fnum and snum as well
In the main class, create a Calculate object using the new operator and the constructor in place.
Call the getAnswer() method with the created Calculate object.
Rest of the code looks fine to me.
Be modular. You could read your program in a much better way.
Here is my modular piece of code.
Two files : Main.java & Calculate.java
Calculate.java
public class Calculate {
private double fn;
private double sn;
private char op;
public double getFn() {
return fn;
}
public void setFn(double fn) {
this.fn = fn;
}
public double getSn() {
return sn;
}
public void setSn(double sn) {
this.sn = sn;
}
public char getOp() {
return op;
}
public void setOp(char op) {
this.op = op;
}
public Calculate(double fn, double sn, char op) {
this.fn = fn;
this.sn = sn;
this.op = op;
}
public void getAnswer(){
double ans;
switch (getOp()){
case '+':
ans = add(getFn(), getSn());
ansOutput(ans);
break;
case '-':
ans = sub (getFn(), getSn());
ansOutput(ans);
break;
case '*':
ans = mul (getFn(), getSn());
ansOutput(ans);
break;
case '/':
ans = div (getFn(), getSn());
ansOutput(ans);
break;
default:
System.out.println("--------------------------");
System.out.println("Invalid choice of operator");
System.out.println("--------------------------");
}
}
public static double add(double x,double y){
return x + y;
}
public static double sub(double x, double y){
return x - y;
}
public static double mul(double x, double y){
return x * y;
}
public static double div(double x, double y){
return x / y;
}
public static void ansOutput(double x){
System.out.println("----------- -------");
System.out.printf("the answer is %.2f\n", x);
System.out.println("-------------------");
}
}
Main.java
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Where you have written the code
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.
you seem to have not created an main method, which should probably look something like this (i am not sure)
class RunThis
{
public static void main(String[] args)
{
Calculate answer = new Calculate();
answer.getNumber1();
answer.getNumber2();
answer.setNumber(answer.getNumber1() , answer.getNumber2());
answer.getOper();
answer.setOper(answer.getOper());
answer.getAnswer();
}
}
the point is you should have created a main method under some class and after compiling you should run the .class file containing main method. In this case the main method is under RunThis i.e RunThis.class.
I am new to java this may or may not be the right answer, correct me if i am wrong