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.
Related
I´m new to programming and I have this task to implement a simple booking System for bus tickets.
We´re supposed to implement a method that adds new bus routes using the attributes: busNumber, start, destination, price, currency. To save the bus routes I´m using an arraylist and save new objects like this:
Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))
My issue now is working with those objects since they don´t have a name. I don't know the exact number of objects, so I have to do it this way (i think so at least). Where the issue occurred is at the method "remove", that is supposed to remove a bus route. I thought I could use an Iterator to iterate through the ArrayList and compare the busNumbers but it´s not working.
Another issue I have is, that when I want to print all the objects in my Array list it just prints the last object as many times as there are objects in my ArrayList. Also, my method and attributes are all static now otherwise I wouldn´t know how to use them in another class.
Does anybody has some advice for a newbie please?
My Code is below:
import java.util.ArrayList;
import java.util.Iterator;
public class Booking {
static int busNumber;
static int customerID = 1; //First customerID starts with 1
static String name;
static double price;
static int invoiceNumber = 1; //First invoicenumber starts with 1.
static String start;
static String destination;
static Currency currency;
static ArrayList<Booking> bookable = new ArrayList<Booking>();
//Constructor
public Booking(int busNumber, String start, String destination, double price, Currency currency) {
this.busNumber = busNumber;
this.start = start;
this.destination = destination;
this.price = price;
this.currency = currency;
}
public int getBusNumber() {
return busNumber;
}
public static void add(Booking add) { // add-method. Adds the bus routes to the booking system
bookable.add(add);
}
public static void remove(int busNumber) { // Here´s one of my issues. That´s what i have.
Iterator<Booking> it = bookable.iterator();
if ( == busNumber) {
bookable.remove(it);
}
}
public static void listRoute() {
for (Booking element : bookable) {
Terminal.printLine(toString(element));
}
}
public static String toString(Booking element) {
return "000" + busNumber + " " + start + " " + destination + " " + price + " " + currency;
}
}
My second class which is later supposed to be the UI:
public class Input {
public static void main(String[] args) {
Booking.add(new Booking(1, "Mannheim", "Karlsruhe", 2.05, Currency.EUR));
Booking.add(new Booking(2, "Heidelberg", "Karlsruhe", 3.05, Currency.JPY));
Booking.add(new Booking(3, "Germersheim", "Karlsruhe", 4.05, Currency.USD));
Booking.listRoute();
}
}
The Output is: "0003, "Germersheim", "Karlsruhe", 4.05, Currency.USD" 3 times..
I am trying to have my driver class inherit the information from two different classes. I have to use the formula className objectName = new className(input parameters) to instantiate one of the classes. But I keep getting the symbol not recognized error.
I'm not sure how I could fix this problem. I tried creating an import statement, but the other two classes are part of the same package. I have also tried using the extends keyword, but also noluck
public class Corgi extends Dog {
// additional class variables
private static int weight;
private static int age;
// constructor
public Corgi(String type, String breed, String name, int pounds, int years) {
// invoke Dog class (super class) constructor
super(type, breed, name);
weight = pounds;
age = years;
}
// mutator methods
public static int setWeight(int pounds){
weight = pounds;
return pounds;
}
public static int setAge(int years){
age = years;
return years;
}
// override toString() method to include additional dog information
#Override
public String toString() {
return (super.toString() + "\nThe Corgi is " + age +
" years old and weighs " + weight + " pounds.");
}
}
public class Dog {
// class variables
private static String type;
private static String breed;
private static String name;
private static String topTrick;
// constructor
public Dog(){
type = "none";
breed = "none";
name = "none";
}
// methods
public static String setTopTrick(String trick){
topTrick = trick;
return trick;
}
// method used to print Dog information
public String toString() {
String temp = "\nDOG DATA\n" + name + " is a " + breed +
", a " + type + " dog. \nThe top trick is : " +
topTrick + ".";
return temp;
}
}
public class Main
{
public static void main(String[] args) {
Corgi tricker = new Corgi();
tricker.setTopTrick("Backflip");
System.out.println(tricker);
}
}
I am expecting to be able to have the main class inherit Corgi's info with the Corgi tricker = new Corgi(); statement. But I keep getting the error:
Main.java:6: error: cannot find symbol
Corgi tricker = new Corgi("Hunting", "Shiba", "Simon", 30, 7);
^
symbol: class Corgi
location: class Main
In your Corgi class you need to remove variables from super()
public Corgi(String type, String breed, String name, int pounds, int years) {
// invoke Dog class (super class) constructor
super();
weight = pounds;
age = years;
}
2.Then you have to add values in Corgi(); which is in `Main class'
public static void main(String[] args) {
Corgi tricker = new Corgi("puppy", "Husky", "Alex", 15, 1);
tricker.setTopTrick("Backflip");
System.out.println(tricker);
}
output -:
DOG DATA
none is a none, a none dog.
The top trick is : Backflip.
The Corgi is 1 years old and weighs 15 pounds.
Sorry everyone. My code wasn't the problem. I tried using the code in a different compiler and it worked just fine. I did tweak my code a little with Kalana's advice. Thanks everyone.
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.
I am a beginner in Java and I am trying to learn the concept of a List by creating simple programs. So basically, I have two java files: CallListClass.java and TestList.java.
CallListClass.java
package javaSrc;
import java.util.*;
public class CallListClass {
public static void main(String[] args){
List<TestList> tl = new ArrayList<TestList>();
//TestList tlobj = new TestList();
TestList l1 = new TestList();
l1.setname("MARY");
System.out.println("Value of name::"+l1.getname());
tl.add(l1.getname()); //Error on this line-The method add(TestList) in the type List<TestList> is not applicable for the arguments (String)
}
}
TestList.java
package javaSrc;
public class TestList{
int age;
String name ="";
int empid;
int getage()
{
return this.age;
}
String getname()
{
return this.name;
}
int getempid()
{
return this.empid;
}
void setage(int age)
{
this.age = age;
}
void setname(String name)
{
this.name = name;
}
void setempid(int empid)
{
this.empid = empid;
}
}
Can anyone tell me why List's add method is giving the above compilation error? Also please let me know if my TestList.java is possible in a real world scenario?
I am thinking of creating a list with name,age and empid. Is there a way we can achieve this?
Change the error line to
tl.add(l1);
It's just that simple.
Everything you did is correct until the above line. You created a class TestList, which is basically a group of name, age and empid. You created a list that can store TestList: new ArrayList<TestList>(). The only thing you failed to do was to put stuff into the list. You don't need to put each name, age and empid into the list, just put the whole l1 object in there, because that is what the ArrayList is supposed to store!
Also, there are some other small issues. You should name your class a more meaningful name than TestList. You should also rename getname to getName, getage to getAge, etc.
The method l1.add() has the signature List<TestList>.add(TestList value), so the added value should be of type TestList. However, the result of l1.getName() is a String and can therefore not be added to the list. For example:
List<MyObject> list = new ArrayList<>();
MyObject obj = new MyObject();
//Not correct
list.add(obj.getClass());
list.add(obj.toString());
//Correct
list.add(obj);
Replacing tl.add(l1.getname()); with tl.add(l1); should solve your problem.
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.