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
Related
I want to read in a csv file once, and later request information from it. Later this is going to be in a website/Rest-API.
I am new to the world of java-website-development, but I hope this way is the way to do it:
I create a class that reads in the data (I want that this happens once, so I use a static variable for that).
When the csv is read in by opencsv, the data are stored in a bean. For this I create the Car-class as a bean.
I use a third class to do the processing and the logic. Later this is supposed to be the website that processes the data.
Here are the classes:
The bean:
Car.java
package org.example;
import com.opencsv.bean.CsvBindByName;
import java.math.BigDecimal;
public class Car {
#CsvBindByName
private int id;
#CsvBindByName(column = "name")
private String brand;
#CsvBindByName
private BigDecimal price;
public int getId() {
return id;
}
public String getBrand() {
return brand;
}
public BigDecimal getPrice() {
return price;
}
public void setId(int id) {
this.id = id;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setBrand(String brand) {
this.brand = brand;
}
#Override
public String toString() {
return "Car{" +
"id=" + id +
", brand='" + brand + '\'' +
", price=" + price +
'}';
}
}
abc.csv:
id,name,price
1,Audi,52642
2,Mercedes,57127
3,Skoda,9000
4,Volvo,29000
5,Bentley,350000
6,Citroen,21000
7,Hummer,41400
8,Volkswagen,21600
9,Toyota,26700
ReadCSVFile.java
package org.example;
import com.opencsv.bean.CsvToBeanBuilder;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
public class ReadCSVFile {
static String fileName = "src/main/resources/abc.csv";
public static List<Car> cars;
static {
try {
cars = new CsvToBeanBuilder(new FileReader(fileName))
.withType(Car.class).build().parse();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
Main.java
package org.example;
import com.opencsv.CSVReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
System.out.println();
for (Car car : ReadCSVFile.cars) {
System.out.println(car.toString());
}
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
System.out.println("Enter id to get more details about the car.");
int id_number = sc.nextInt();
System.out.println("Your selected id is "+id_number);
Car selected_car = null;
for (Car car : ReadCSVFile.cars) {
if (car.getId() == id_number) {
selected_car = car;
}
}
if (selected_car == null) {
System.out.println("No car found that matches your id.");
} else {
System.out.println("Selected car matches: " + selected_car.toString());
}
System.out.println();
}
}
}
This works fine, but when I add a constructor in the Car.java
public Car(int id, String brand, BigDecimal price) {
this.id = id;
this.brand = brand;
this.price = price;
}
then I get an error: Caused by: java.lang.RuntimeException: com.opencsv.exceptions.CsvBeanIntrospectionException: Instantiierung des angegebenen Typs (und eventuell vorhandene Untertypen) ist unm�glich.
I do not know how to switch this error message to English; it means something like "It is not possible to instantiate the wanted type (and possibly also present subtypes)".
Does opencsv generally have problems with constructors? Is this a wanted behaviour? Do beans generally lack constructors? Because I feel like I want to have a constructor in the future in my class...
Please feel free to add comments about my general approach how I organize the code.
OpenCSV‘s introspection works by creating object instances via a no-args constructor. Therefore, you are required to provide one, even if you have specialized constructors as posted in your question.
By default, there will be a no-arg constructor in Java, however, once you have a custom one, the no-arg one must be explicitly defined in your Java class.
To cure the problem, just add back in a no-arg constructor, eg in a protected form:
protected Car() {}
This way, the code should just work fine at runtime.
Excuse me, I'm new to this.
I am currently using BlueJ and going through YouTube tutorials on Eclipse, but I need to use BlueJ for my assignment
I simply have to make a GUI called GadgetShop (which I have done), and it has buttons which add info from my Mobile and MP3 class. There is also a class called Gadget, which is the super-class.
So the issue I am having is with ArrayLists and gathering the info from the classes to display it in the Text Boxes I have made. I made an array list but I'm not sure what's wrong, because it says constructor Gadget in class Gadget cannot be applied to given types;
Here's the code needed in the GadgetShop:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class GadgetShop implements ActionListener
{
private JTextField model, price, weight, size, credit, memory, phoneNo, duration, download, displayNumber;
private JButton addMobile, addMP3, clear, displayAll;
//These JTextField's are for the labels
private JTextField model2, price2, weight2, size2, credit2, memory2, phoneNo2, duration2, download2, displayNumber2;
private JFrame frame;
private ArrayList<Gadget> gadgetDetails;
public GadgetShop()
{
makeFrame();
}
public static void main (String args[]){
ArrayList<Gadget> GadgetList = new ArrayList<Gadget>();
Gadget Object = new Gadget();
GadgetList.add(Object.Gadget(model, price, weight, size));
}
public void addGadget(Gadget newGadget)
{
gadgetDetails = new ArrayList<Gadget>();
gadgetDetails.add(newGadget);
model.setText("s6");
My Gadget is this:
/**
* Gadget that is a super class for the Mobile Phone and MP3.
* Needs input for the price, weight, model and size.
*/
public class Gadget
{
// Variables
public double price;
public int weight;
public String model;
public String size;
/**
* Constructor for objects of class Gadget
*/
public Gadget(double ThePrice, int TheWeight, String TheModel, String TheSize)
{
// initialise instance variables
price = ThePrice;
weight = TheWeight;
model = TheModel;
size = TheSize;
}
public double price()
{
return price;
}
public int weight()
{
return weight;
}
public String model()
{
return model;
}
public String size()
{
return size;
}
public void print()
{
System.out.println("The price of the gadget is " + price + " pounds");
System.out.println("The weight is " + weight + " grams");
System.out.println("The model is " + weight);
System.out.println("The size is " + size);
}
}
What does it actually mean so I can fix this, and what's the recommended way to gather information from my classes to be entered into my text boxes when clicking the button? (I know how to activate button on clicks and add the information, but just don't know the best way to retrieve it)
Thank you for reading, I want to learn so this would help me extremely.
Your constructor for Gadget takes arguments:
public Gadget(double ThePrice, int TheWeight, String TheModel, String TheSize)
{
// initialise instance variables
price = ThePrice;
weight = TheWeight;
model = TheModel;
size = TheSize;
}
You cannot simply call new Gadget() because the constructor needs four arguments. You have two options: firstly, you can provide the arguments in your main method:
public static void main (String args[]){
ArrayList<Gadget> GadgetList = new ArrayList<Gadget>();
Gadget object = new Gadget(1.00,20,"a model", "big");
GadgetList.add(object);
}
Substitute whatever values make sense. The other solution is too create another constructor which doesn't take arguments in your Gadget class:
public Gadget() {
//initialize values to default values
price = 1.00
weight = 21
// etc.
}
You still have to fix the main method a little bit:
public static void main (String args[]){
ArrayList<Gadget> GadgetList = new ArrayList<Gadget>();
Gadget object = new Gadget();
GadgetList.add(object);
}
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.
I'm a beginner Java programmer and I'm trying to check whether I've successfully copied an instance of Person in a linked list stored in class Clients to the linked list called passengers inside an instance of class Boat by having Boat print out the contents of it's linked list.
I am using the method givePassengers() from class Boat to have the Boat class printout it's passengers linked list contents.
However when I attempt to do so I am encountering the error 'non-static method givePassengers() cannot be referenced from a static context' and I'm not sure what to write to solve that problem. I've listed what I believe to be the problem code below. Any assistance is greatly appreciated.
I have marked important code with '// !!'
This is the class that contains the linked list of boats
import java.io.*;
import java.util.*;
public class Base implements Serializable
{ private LinkedList<Boat> boats = new LinkedList<Boat>();
private Clients clients = new Clients();
public void setup() // !! Here are the instances of the boat class
{ boats.add(new Boat(1, "Ed", 2));
boats.add(new Boat(2, "Fred", 7));
boats.add(new Boat(3, "Freda", 5)); }
public void showpassengers() {
for (Boat i: boats) `// !! The for each loop cycles through each boat to check for passengers`
Boat.givePassengers(); // !! This line produces the error
}
Here is the boat class
import java.io.*;
import java.util.*;
public class Boat implements Serializable
{ private int id;
private String pilot;
private int stops;
private LinkedList<Person> passengers = new LinkedList<Person>();
private double rate = 10.00;
public int scannableId = this.id;
public Boat(int id, String pilot, int stops)
{ this.id = id;
this.pilot = pilot;
this.stops = stops; }
public void givePassengers () {
System.out.println(passengers); // !! this line is supposed to print out the contents of the boat classes' linked list so I can check that it worked.
}
Here is the Person class
import java.io.*;
import java.text.*;
public class Person implements Serializable
{ private String name;
private int id;
private double cash = 100.00;
private int start = 0;
private int end = 0;
private double charge = 0;
public Person(String name, int id)
{ this.name = name;
this.id = id + 100; }
}
Here is the class that contains the linked list of Person
import java.io.*;
import java.util.*;
public class Clients implements Serializable
{ private LinkedList<Person> clients = new LinkedList<Person>();
private int id = 1;
public Clients() `// !! Here are the instances of Person in the class clients`
{ clients.add(new Person("Homer", id++));
clients.add(new Person("Marge", id++));
}
)
And here is the root class if that helps
import java.io.*;
public class Root
{ public Root() {
new Base();
}
public static void main(String[] args)
{ new Root(); }
private Base base;
}
Your problem is here:
for (Boat i: boats)
Boat.givePassengers(); // !! This line produces the error
You need to say i.givePassengers() to reference the specific instance of the class Boat. There's a good primer on the difference between classes and objects here.
You can't call givePassengers() statically from Boat, it's not a static method. You need to call it from an instance of Boat. Replace Boat.givePassengers(); with i.givePassengers(); within your foreach loop. This will cause the currently selected Boat instance to run givePassengers().
I created 2 instances of my class player, but it seems as though the last instance created always takes over (overlaps?) All of the other objects, what is the issue here?
Here is the program:
public class Test
{
public static void main (String[] args)
{
Player player1 = new Player("Player 1");
Player player2 = new Player("Player 2");
Player player3 = new Player("Player 3");
System.out.println(player1.getName());
}
}
This is the output
Player 3
And this is the class
import java.util.Scanner;
import java.util.Random;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Player
{
public static String name;
public static int score;
public static Die[] dice = new Die[5];
public static JRadioButton[] rerollButton = new JRadioButton[5];
//----------------------------------------------------------------
// Constructor - initialize values
//----------------------------------------------------------------
public Player(String n)
{
name = n;
score = 0;
// initialize all dice and rerollButtons in their respective arrays
for (int i = 0; i < 5; i++) {
dice[i] = new Die();
rerollButton[i] = new JRadioButton();
}
}
public String getName()
{
return name;
}
}
I have tried to look for other similar questions but every one I found was far to complex for me to really understand.
The attributes in your Player class such as name,score, dice etc are defined as class variables(static) instead of instances variables(non-static). Class/static variables are shared by all the objects and hence you see that behavior. Try changing this:
public static String name;
to
public String name;
Make a wise decision what you need to declare as class variable and what as member variable. Learn more about instance and class members here:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
That's because name is a static field in your Player class. And the static fields are shared by all the instances of a class. Therefore, you need to make the name as an instance variable, so that each instance will have their own copy of the it.
public String name; // Now each instance will have its own copy of name
and I'm guessing that the same needs to be done for score as well.
public int score;
public static String name;
should be
public String name;
or even better
private String name;
Because, your field is static,
public static String name;
To change the name with object make it as instance(non-static)
public String name;