When i try to compile an aggregation program , i receive an error saying "class,interface,enum expected". Here is my code. please help me solve this issue.
class employee
{
private String name;
private String address;
private float salary;
public employee(String na, String add,float sal)
{
name = na;
address = add;
salary = sal;
}
public void showEmpDetails()
{
System.out.println("Name " + name);
System.out.println("Address " + address);
System.out.println("Salary " + salary );
System.out.println();
}
}
import java.util.vector;
class company
{
private String comname;
private vector vt;
public company(String na)
{
comname = na;
vt = new vector();
}
public void addEmployee(employee e)
{
vt.addElement(e);
}
public void showComDetails()
{
System.out.println("Company Name " + comname);
int x = vt.size();
int y = 0;
while(y<x)
{
object e = vt.elementAt(y);
e.showEmpDetails();
y++;
}
}
}
public class demo
{
public static void main(String[] args)
{
employee e1 = new employee("Ashan","Kandy",2000.0f);
employee e2 = new employee("Steve","California",2500.0f);
employee e3 = new employee("Elon","South Africa",2500.0f);
company c1 = new company("Apple");
c1.addEmployee(e1);
c1.addEmployee(e2);
c1.addEmployee(e3);
c1.showComDetails();
}
}
Note:- i receive only one error. and also can anybody tell me why can't i have more than one public class in java.
Well, your code has more than one error actually. The reason for your specific error is that import should be at beginning of the file, not in the middle.
And my understanding of why only one public class is allowed for each file is:
It makes things clearer.
By reading the class name and document to this class, you could quickly know what the whole file is used for. If we allow multiple public classes in one file, like C++, then we have to jump inside of the file to understand it.
Notice Java is a strong object-oriented language, i.e. everything in Java is Object. So when importing, you are importing a file. It would be more complicated if one file contains multiple public classes.
It simplify testing.
Each public class could have a main function. And you could run any main function of a file Demo.java simply by java Demo. This is really nice, so that you could write test code, or example of usage in main function to show other contributor how this class should be used.
There have to be other more in-depth reason for single public class in Java. But these are my perspective.
Related
i was reading a book and it has an example which has 2 main methods in its file in different classes , one main method is for testing purposes but i cant understand a way to compile classes individually if there is any way please suggest me
here's the code
/**
* #author achintya
*/
public class StaticTest
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("tom",4000);
staff[1] = new Employee("dick",60000);
staff[2] = new Employee("harry",65000);
for(Employee e : staff)
{
e.setId();
System.out.println("name" + e.getName() + ",id=" + e.getId() + ",salary=" + e.getSalary());
}
int n = Employee.getNextId();
System.out.println("next available id=" + n);
}
}
class Employee
{
private static int nextId = 1;
private String name;
private double salary;
private int id;
public Employee(String n,double s)
{
name = n;
Salary = s;
id = 0;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int getId()
{
return id;
}
public void setId()
{
id = nextId;
nextId++;
}
public static int getNextId()
{
return nextId;
}
public static void main(String[] args){
Employee e = new Employee("harry",50000);
System.out.println(e.getName() + " " + e.getSalary());
}
}
In your example, you have two classes in the same single source code file.
That is perfectly fair, as only public classes need to go into their own files. This means that you can have N non-public classes in the same source code file.
When things get compiled, there is no more notion of "coming out of the same .java file" though.
You end up with StaticTest.class and Employee.class. And the JVM simply allows you to also invoke a main() method on a non-public class.
But: there is simply no compiling the individual classes. The java compiler works on "file granularity". It will always compile the whole file you give to it, and there is no way for you to say: compile that file, but only the non-public class within.
The short answer: you can't compile individual classes.
The long answer:
You can still run the classes individually.
When you compile the file, you won't see any changes. However, java will compile 2 different classes, StaticTest in the StaticTest.class file, and Employee in the Employee.class file.
Then, to run Employee.class, just run java Employee, and the main method of Employee will run. Read https://stackoverflow.com/a/27313798/13084867 for more
Here are the cmd commands. They can easily be replicated in a Linux environment:
C:\...\Folder> javac StaticTest.java
C:\...\Folder> java StaticTest
I am trying to add a new train to my arraylist but upon adding the train, the existing content of the arraylist gets overwritten by the new input. This results in having only one item in the arraylist without being able to add more without overwriting the other. As I do not quite know what the source of this problem in the code is, I came looking for help here.
Within this class the train is being made:
public class RCommand extends RBaseListener {
Company mycompany = new Company("traincompany");
#Override
public void enterNewtraincommand(RParser.NewtraincommandContext ctx) {
System.out.println("Now creating new train " + ctx.getText());
mycompany.addTrainTo(new Train(ctx.getChild(2).toString()));
System.out.println(mycompany.getTrains().size());
}
}
In this class the train is supposed to be added to the list.
public class Company{
private String name;
List<Train>trains = new ArrayList<Train>();
public void addTrainTo(Train train) {
trains.add(train);
for (Train t :trains) {
System.out.println(t.getName());
}
}
}
Simply test for your class Company to see if if work
public class Test {
Company company = new Company();
public static void main(String[] args) {
Test test = new Test();
test.start();
}
private void start() {
System.out.println("IT work");
company.addTrainTo(new Train("One"));
System.out.println("End first add");
company.addTrainTo(new Train("two"));
System.out.println("End second add\n");
System.out.println("Follow example will not work");
company = new Company();
company.addTrainTo(new Train("One"));
System.out.println("End first add");
company = new Company(); // <--- create the ERROR
company.addTrainTo(new Train("two"));
System.out.println("End second add");
}
}
Suppose we have train as is:
public class Train {
private String name;
public Train(String name) {
this.name = "Train" + name;
}
public String getName() {
return name;
}
}
Output is:
IT work
Train One
End first add
Train One
Train two
End second add (it work fine)
Follow example will not work
Train One
End first add
Train two
End second add<- we miss the first train because we recreate the company instance
So it work.
So the error is not in this class Company.
Check if the caller of Company recreate the class Company before adding new train
Check class train if it has something strange (static attribute for name or similar)
Looks like new "trains" object is being created for each addition. After adding, try to print the address of "trains" object to find out for sure. You can print the address by System.out.println("trains address is: " + trains)
You did't pass for us all your code required but I think, you should create a Company constructor with your train List.
Something like that:
public class Company{
private String name;
List<Train>trains;
public Company(String name, List<Train> trains){
this.name = name;
this.trains = trains;
}
...
}
Then in your RCommand class use your new Constructor
Company mycompany = new Company(new ArrayList<Train> ,"traincompany");
And it will be fine. Your mistake in code is creating new trains list every time by calling new operator.
I need help with a specific problem in my class project. The goal of the project is to create a program in which you can register how much shares you own. Information that's required is the company name, how many shares you own and their respective value. I created a GUI class and a class where the information is transferred to. The input comes from a private void. I'm having trouble finding a way to transfer the input from the private void to a an arraylist in a class outside it.
Here is how I initialized the arraylist in the GUI class.
public class GUISharePortfolio_1 extends javax.swing.JFrame {
ArrayList<SharePackage.Share> Package = new ArrayList<SharePackage.Share>();
Next is how I get the company name, number of shares and their value from the GUI. Since it is a private void I have to transfer that information to the SharePackage class.
private void CreatePortfolioButtonActionPerformed(java.awt.event.ActionEvent evt) {
String name;
double number;
double value;
name = CompanyNameField.getText();
number = Double.parseDouble(NumberOfSharesField.getText());
value = Double.parseDouble(ValueOfShareField.getText());
Package.CompanyName(name);
Package.NumberOfShares(number);
Package.ValueOfShare(value);
}
I'm getting an error saying "cannot find symbol" under the CompanyName, NumberOfShares and ValueOfShare.
The public class to which the info should be transferred is this:
package shareportfolio;
import java.util.ArrayList;
public class SharePackage
{
private ArrayList<Share> Package = new ArrayList<Share>();
public class Share
{
private String companyname;
private double numberofshares;
private double valueofshare;
Share(String companyname, double numberofshares, double valueofshare)
{
this.companyname = companyname;
this.numberofshares = numberofshares;
this.valueofshare = valueofshare;
}
public void setCompanyName(String name)
{
companyname = name;
}
public String getCompanyName()
{
return(companyname);
}
public void setNumberOfShares(double number)
{
numberofshares = number;
}
public double getNumberOfShares()
{
return(numberofshares);
}
public void setValueOfShare(double value)
{
valueofshare = value;
}
public double getValueOfShare()
{
return(valueofshare);
}
}
}
I would appreciate any help very much.
You have a field named Package, who's type is ArrayList. ArrayList doesn't have a method called CompanyName. What you're probably trying to do is something like:
Package.add(new SharePackage.Share(companyname, numberofshares, valueofshares));
You have two such fields named 'Package', so not sure which one you're trying to add to. Maybe you're under the impression the fields are somehow the same one. They are not.
BTW: Definitely learn Java coding style before submitting this to anyone. You are naming fields with UpperCamelCase which makes it very difficult for a java programmer to read your code.
user1207705 that was the answer. I modified it to:
String name;
double number;
double value;
name = CompanyNameField.getText();
number = Double.parseDouble(NumberOfSharesField.getText());
value = Double.parseDouble(ValueOfShareField.getText());
Package.add(new SharePackage.Share(name, number, value));
Thank you for your help and I will work on Java coding style.
I have scoured many web pages trying to solve this issue, but I am struggling. I don't want someone to fix it for me, I just want someone to point me in the right direction please :). My problem is two-fold, I have an array of objects,I want to pass each object to my Teams class, so that the team name can be saved. This code doesn't compile, error concerns line: "Teams(MainmenuTest[]) teamName() {"
error is '.class' expected
followed by
';' expected
I can get serialisation to work when the objects are created in my Teams class, (if I comment out the code for passing objects), and it does create a .ser file in the directory I have specified.
Here are the snippets of code:
public class Teams implements java.io.Serializable{
public Teams(){
// constructor
MainmenuTest[] teamName;
Teams(MainmenuTest[]) teamName() {
this.teamName = teamName;
}
}
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name + " " + address);
}
} // end Teams class
public class premierLeagueClubs{
public String club;
Teams[] teamName = new Teams[19];
premierLeagueClubs f = new premierLeagueClubs();
Teams t = new Teams(f,teamName);
public String arsenal(){
teamName[0].club = "Arsenal";
System.out.println("You are the new manager of" + club);
return club;
} // end method arsenal
Here is the MainmenuTest code:
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class MainmenuTest extends premierLeagueClubs{
int choice;
public MainmenuTest(){
//constructor
}
public static void main(String args[]){
MainmenuTest team = new MainmenuTest();
team.getInput();
} // end main method
Here is my code
class Bomb {
static String description = "bomb description";
static int id = 1;
private String name;
private int size;
public static void Bomb() {
id++;
System.out.println(" " + description + " " + id);
}
public void setName(String name) {
this.name = name;
}
public void setSize(int size) {
this.size = size;
}
public void printout() {
System.out.println(" " + name + size);
}
}
public class array {
public static void main(String args[]) {
Bomb.Bomb();
Bomb detenator = new Bomb();
Bomb destroyer = new Bomb();
destroyer.setName("hr4");
destroyer.setSize(43);
detenator.setName("m1s");
detenator.setSize(34);
detenator.printout();
destroyer.printout();
}
}
I want the description to print with each bomb object. but the description prints by itself.
any one got any idea how to fix that?
also please suggest any alternative ways I could've written this code, but don't make it to complicated. i just started learning java so i probably wont understand complex stuff.
I short, there are no "static constructors".
You may want something that references a static member, like this:
public Bomb() {
id++;
System.out.println(" " + Bomb.description + " " + id);
}
Please go over the Java tutorial of constructors:
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
Your definition of constructor is completely messed up.
As #Reut Sharabani mentioned there is no something like static constructor. You are using constructors to initiate object of a class. And static let you use method just by calling ClassName.staticMethod() without creating object of the class (one ruling out another). If static constructor would exist you would be able to write something like, for example, ClassName.ClassName() which make no sense.
Constructors are not returning any value, so declaring them as void is an error. Again constructor is used to initialize your object with some values (but unnecessary)