Having trouble with MAIN please advise [duplicate] - java

This question already has answers here:
"Error: Main method not found in class MyClass, please define the main method as..."
(10 answers)
Closed 9 years ago.
Sorry guys I am new to Java and I have an issue with my code. I have read through the threads and have seen many examples regarding this specific error (java.lang.NoSuchMethodError: main Exception in thread "main"). I just cant seem to wrap my head around where I would add (static void main(String[] args)) to the code. If you guys can point me in the right direction I would really appreciate it.
Here is what I have:
public class Employee {
String name;
String department;
double hourlyRate;
Employee(String name, String department, double hourlyRate) {
this.name = name;
this.department = department;
this.hourlyRate = hourlyRate;
}
public void setDepartment(String department) {
this.department = department;
}
public void setHourlyRate(double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public String getNameAndDepartment() {
return name + " " + department;
}
double weeklyPay(int numOfHourWorked) {
if (numOfHourWorked < 40) {
return (numOfHourWorked * hourlyRate);
} else
return (40 * hourlyRate);
}
}
class UnionEmployee extends Employee {
double dues;
UnionEmployee(String name, String department, double hourlyRate, double dues) {
super(name, department, hourlyRate);
this.dues = dues;
}
public void setDues(double dues) {
this.dues = dues;
}
double weeklyPay(int numOfHourWorked) {
if (numOfHourWorked <= 40) {
return (super.weeklyPay(numOfHourWorked));
} else
return ((super.weeklyPay(40) + ((numOfHourWorked - 40) * hourlyRate * 1.5)) - dues);
}
}
class CommissionEmployee extends Employee {
double commisionRate;
double salesAmount;
CommissionEmployee(String name, String department, double hourlyRate) {
super(name, department, hourlyRate);
}
public void setCommisionRate(double commisionRate) {
this.commisionRate = commisionRate;
}
public void setSalesAmount(double salesAmount) {
this.salesAmount = salesAmount;
}
double weeklyPay(int numOfHourWorked) {
return (super.weeklyPay(numOfHourWorked) + (commisionRate * salesAmount));
}
}
class TestEmployee {
UnionEmployee uEmp = new UnionEmployee(null, null, 0, 0);
CommissionEmployee cEmp = new CommissionEmployee(null, null, 0);
Employee emp = new Employee(null, null, 0);
void display(Employee emp, int numOfHourWorked) {
System.out.println("Name and department :" + emp.getNameAndDepartment ());
System.out.println("Weekly pay of employee :"
+ emp.weeklyPay(numOfHourWorked));
}
void display(UnionEmployee uEmp, CommissionEmployee cEmp,
int numOfHourWorked) {
System.out.println("Weekly Pay for UnionEmployee"
+ uEmp.weeklyPay(numOfHourWorked));
System.out.println("Weekly Pay for UnionEmployee"
+ cEmp.weeklyPay(numOfHourWorked));
}
}
OK so I started by separating each class into a different file. In looking through the Java tutorials it said to add static void main(String[] args) the way the tutorial had it setup was like this:
public class Misc {
static void main(String[] args) {
//body
}
}
So I did this:
class TestEmployee {
static void main(String[] args) {
UnionEmployee uEmp = new UnionEmployee(null, null, 0, 0);
CommissionEmployee cEmp = new CommissionEmployee(null, null, 0);
Employee emp = new Employee(null, null, 0);
void display(Employee emp, int numOfHourWorked) {
System.out.println("Name and department :" + emp.getNameAndDepartment ());
System.out.println("Weekly pay of employee :"
+ emp.weeklyPay(numOfHourWorked));
}
void display(UnionEmployee uEmp, CommissionEmployee cEmp,
int numOfHourWorked) {
System.out.println("Weekly Pay for UnionEmployee"
+ uEmp.weeklyPay(numOfHourWorked));
System.out.println("Weekly Pay for UnionEmployee"
+ cEmp.weeklyPay(numOfHourWorked));
}
}
}
Still get the same error : (java.lang.NoSuchMethodError: main Exception in thread "main").
OK I add public but now I get this:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
void is an invalid type for the variable display
Syntax error on token "(", ; expected
Duplicate local variable emp
Syntax error on token ",", ; expected
Syntax error on token ")", ; expected
void is an invalid type for the variable display
Syntax error on token "(", ; expected
Duplicate local variable uEmp
Syntax error on token ",", ; expected
Duplicate local variable cEmp
Syntax error on token ",", ; expected
Duplicate local variable numOfHourWorked
Syntax error on token ")", ; expected
at TestEmployee.main(TestEmployee.java:9)

Your problem with main is that it doesn't exist, and you need to put one in your program for it to run. Put it in the main class, whichever one that is, but while it needs to be inside of the class, inside of the curly braces that define the class, you must also make sure that you don't put it inside of another method.
Above, I'd put it in TestEmployee.
I'd also take care to make sure every class above is declared public and is in its own file. So your code above which contains 4 classes, should be comprised of 4 files.
Edit
Also, be sure to declare your main method as a public method as #Aniket noted in comment below.
Edit 2
You're still not declaring main as a public method.
You have methods embedded within the main method. Remember that in Java you can't do this since all methods need to be class level. Get them out of the main method.
Your code indentation is horrible to say the least, and this will make it very difficult for you or us to see your coding problems. You will want to invest time and effort towards indenting your code properly. If you did this, you would see in an instant that you had methods inside of methods.

Related

I'm getting weird errors for seemingly simple Java code. What am I doing wrong here?

I have a final project for my introduction to software class that is split into parts. For the first part, here are the instructions:
Task 1-1:
Create a Class called Inventory
Consisting of three data members: a part number consisting of 2 letters followed by four numbers (e.g. AB1234), a description
consisting of 5-25 letters describing the item (e.g. wooden
claw-hammer), and a quantity consisting of an integer between 0 and
1000.
Create a default constructor that sets the part number to AA0000, the description to Test Item, and the quantity to zero.
Create a parameterized constructor that sets the part number, description, and quantity to argument values sent to the constructor.
Create set methods for each data member that changes the value of the member to the argument passed to the method. Also create a group
of get methods that retrieve each data member.
Create a method called show part that displays the formatted contents of an object.
Seems simple, yeah? Well obviously I'm doing something wrong but I'm not exactly sure what, could be a minor error or maybe I just don't know what I'm doing somehow. I've tried removing the constructors and certain methods (showPart() in particular) whilst getting the same or similar errors.
Here's my code:
public class InventoryFinal {
public static void main(String[] args) {
String partNo;
String prodDesc;
int quantity;
public InventoryFinal() {
partNo = "AA0000";
prodDesc = "Test Item";
quantity = 0;
}
public InventoryFinal(String s, String s2, int i) {
partNo = s;
prodDesc = s2;
quantity = i;
}
public void setPartNo(String sSet) {
partNo = sSet;
}
public void setProdDesc(String sSet2) {
prodDesc = sSet2;
}
public void setQuantity(int iSet) {
quantity = iSet;
}
public String getPartNo() { return partNo; }
public String getProdDesc() { return prodDesc; }
public int getQuantity() { return quantity; }
public void showPart() {
System.out.println("Item#: " + partNo);
System.out.println("Description: " + prodDesc);
System.out.println("Quantity: " + quantity);
}
showPart();
}
}
The errors it's giving me don't really make a whole lot of sense to me. What am I doing wrong?
File: M:\Intro to Software\InventoryFinal.java [line: 8]
Error: Syntax error on token "public", new expected
File: M:\Intro to Software\InventoryFinal.java [line: 8]
Error: Syntax error on token "{", { expected after this token
File: M:\Intro to Software\InventoryFinal.java [line: 42]
Error: Syntax error, insert "}" to complete ClassBody
File: M:\Intro to Software\InventoryFinal.java [line: 42]
Error: Syntax error, insert ";" to complete Statement
You can not have embedded methods. At the moment you have all fields and methods inside your main method
it should be more like
public class InventoryFinal {
String partNo;
String prodDesc;
int quantity;
public static void main(String[] args) {
//create new instances and call methods from here
}
public InventoryFinal() {
partNo = "AA0000";
prodDesc = "Test Item";
quantity = 0;
}
public InventoryFinal(String s, String s2, int i) {
partNo = s;
prodDesc = s2;
quantity = i;
}
public void setPartNo(String sSet) {
partNo = sSet;
}
public void setProdDesc(String sSet2) {
prodDesc = sSet2;
}
public void setQuantity(int iSet) {
quantity = iSet;
}
} // close class

Method to get an enumvalue with an inputString

I'm studying Enums in Java and I have a question that isn't working well on my code.
I did my Enum with seconds and some names, and, later, I did a method that looks for it inside the Enum class.
The idea is to start a counter (that's why I'm using the integer values on Enum) given the name of the operation.
The code is:
public enum Calculator {
plus(30), minus(21), divide(21), times(30);
public int seconds;
public int getSeconds() {
return seconds;
}
Calculator(int seconds) {
this.seconds = seconds;
}
private String name;
Calculator(String name) {
this.name = name();
}
public static Calculator contains(String name) {
for (Calculator ss : Calculator.values()) {
if (ss.name.equalsIgnoreCase(name)) {
System.out.println(name + " input " + ss.name + " enum");
return ss;
}
}
throw new NullPointerException("Invalid name");
}
}
And I have another class that invokes this method.
The following invoker is:
public static void calcInput(String name) {
try {
Calculator.contains(name);
} catch(NullPointerException e){
System.out.println("Invalid parameter, " + e );
}
The thing is that, any input I use, a right or wrong one, it is answering me a NullPointerException. Where am I commiting the mistake?
Thanks in advance!
I'm going to walk through your code and make some comments. Then I will show you some changes you could make.
public enum Calculator {
// convention is to name enum values as constants: UPPER_CASE_WITH_UNDERSCORES
plus(30), minus(21), divide(21), times(30);
// you should not make instance fields public, but private
// because they should not be accessed directly by any other class (in general)
public int seconds;
// methods, like this 'getter' belong below all constructors
public int getSeconds() {
return seconds;
}
Calculator(int seconds) {
this.seconds = seconds;
}
private String name;
// this constructor is never used by your enum values (plus, minus, divide, times)
// if it were used, the name parameter in the line below this one is never used for anything
Calculator(String name) {
// you are trying to set your name field to the name() of the enum value.
// even though this would work, this is not very useful
// since calling MY_ENUM_VALUE.name() already gives you its name
this.name = name();
}
// a method like 'contains' usually returns a boolean value to indicate if this instance does or does not
// contain the parameter you provided. Having a 'contains' method which returns a Calculdator instance is
// confusing to say the least. A better name (judging from the method implementation) would be 'forName'
// then you could do:
// Calculator bla = Calculator.forName("Minus");
// System.out.println(bla == Calulcator.minus);
// which would print "true"
public static Calculator contains(String name) {
for (Calculator ss : Calculator.values()) {
if (ss.name.equalsIgnoreCase(name)) {
System.out.println(name + " input " + ss.name + " enum");
return ss;
}
}
// Opinions are mixed on whether you should throw NullPointerExceptions from your application code
// I personally choose to throw IllegalArgumentException in cases like this
throw new NullPointerException("Invalid name");
}
}
Here is a new version of the code which might do what you expect. I don't understand what the 'seconds' values have to do with the calculator operations though.
public enum Calculator {
PLUS(30),
MINUS(21),
DIVIDE(21),
TIMES(30);
private int seconds;
Calculator(int seconds) {
this.seconds = seconds;
}
public int getSeconds() {
return seconds;
}
public static Calculator forName(String name) {
return valueOf(name.toUpperCase());
}
}
The app class:
public class App {
public static void main(String[] args) {
Calculator calculator = Calculator.forName("Minus");
System.out.println(calculator + " seconds = " + calculator.getSeconds());
}
}
The output is:
MINUS seconds = 21

Why can't I seem to find the error in my program when compiling. Help needed

The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.

Having more than one ArrayList

Hello everyone today am trying to do this in my ArrayList and i know it is possible but it is giving me an exception at main. Now am wondering how am i doing it wrong or what is the best way to do it. Am trying to have An ArrayList and inside the ArrayList I have another one and i give it a variable.
import java.util.ArrayList;
import java.util.Collection;
public class Example3 {
public static void main(String[] args) {
ArrayList<ArrayList<Family>> smallFamily = new ArrayList<ArrayList<Family>>();
smallFamily.addAll((Collection<? extends ArrayList<Family>>) (new Family("John",89 )));
smallFamily.addAll((Collection<? extends ArrayList<Family>>) new Family ("Smith", 78)));
for(ArrayList<Family> s: smallFamily){
System.out.println(s);
}
}
Now bellow is my Family Class and in my family this are the values
public class Family {
public String Name;
public int weight;
public Family(String Name, int weight){
this.Name = Name;
this.weight = weight;
}
public String toString(){
return ("The name is " + this.Name + "The weight is: " + this.weight);
}
}}
The exception being thrown when i compile and run my programme is
Exception in thread "main" java.lang.ClassCastException: Examples.Family cannot be cast to java.util.Collection
at Examples.Example3.main(Example3.java:9)
Now am learning Java on my own and don't have anyone i can ask. Any kind of help will be appreciated.
You are trying to convert an object into a collection. This does not work. Rather, you need to do this:
smallFamily.add(new ArrayList<Family>(1) {{add(new Family("", 0));}});
This will create an ArrayList which adds new Family("", 0) when it is created. Then, it will add this arraylist to the smallFamily arraylist.
Now Why you get this line here
smallFamily.addAll((Collection<? extends ArrayList<Family>>) (new Family("John",89 )));
simply it because the computer couldnt understand what you were doing so it casted for you. Or you casted :). Now trying to convert an object into a collection does not work.
Rather you need to try this
public class Example3 {
public static void main(String[] args) {
ArrayList<ArrayList<Family>> smallFamily = new ArrayList<ArrayList<Family>>();
smallFamily.add(new ArrayList<Family>(2222) {{add(new Family("smith ", 0));}});
smallFamily.add(new ArrayList<Family>(333) {{add(new Family("john ", 0));}});
for(ArrayList<Family> s: smallFamily){
System.out.println(s);
}
}
}
when you add your Family Class
public class Family {
public String Name;
public int weight;
public Family(String Name, int weight){
this.Name = Name;
this.weight = weight;
}
public String toString(){
return ("The name is " + this.Name + "The weight is: " + this.weight);
}
}
The output should be
[The name is smith The weight is: 0]
[The name is john The weight is: 0]
Hope thats what you anticipated.

Error: 'void' type not allowed here [duplicate]

This question already has answers here:
What causes "'void' type not allowed here" error
(7 answers)
Closed 10 months ago.
I'm learning to use classes and part of my assignment is to make this Car class. I'm getting an error on line 6 where I attempt to print of the results of the methods within the class. I think this means that I'm attempting to print something that doesn't exist and I suspect it's the mileage method. I tried changing it to return miles, but that didn't work either. Any ideas?
public class TestCar {
public static final void main(String args[]) {
Car c = new Car ();
c.moveForward(4);
System.out.println ("The car went" + c.mileage() + "miles."); // <-- L6
}
}
class Car {
public int miles = 2000;
public void moveForward(int mf) {
if (miles != 2000) {
miles += mf;
}
}
public void mileage() {
System.out.print(miles);
}
}
The error message is telling you exactly what is wrong -- you're trying to extract a result from a method that does not return a result.
Instead, have the mileage() method return a String, not print out a String.
public String mileage() {
return String.valueOf(miles);
}
Myself, I'd make this a getter method, and instead would do:
public int getMiles() {
return miles;
}
Car.mileage() is void, i.e., does not return anything. It needs to return something, like in:
public int mileage() {
return miles;
}

Categories