Java - Cannot find symbol constructor - java

I'm completely new to Java, so I'm sorry if my question is dumb. Im working on this assignment, and I've been reading about main methods for hours now, but I just cant figure it out. I put some of my code below. I might be way off here, but what I'm hoping to accomplish is to get the main method to start the constructor, but when I compile I get an error saying "cannot find symbol - constructor Player". Now, Im guessing this has something to do with the string parameters of the constructor, but I'm all out. If anyone could shed some light on this, probably very simple problem, I'd be very happy :)
public class Player {
private String nick;
private String type;
private int health;
public static void main(String[] args)
{
Player player = new Player();
player.print();
}
public Player(String nickName, String playerType)
{
nick = nickName;
type = playerType;
health = 100;
System.out.println("Welcome " + nick +" the " + type + ". I hope you are ready for an adventure!");
}
public void print()
{
System.out.println("Name: " + nick);
System.out.println("Class: " + type);
System.out.println("Remanining Health: " + health);
}

Player has no no-arg constructor, you could use:
Player player = new Player("My Nickname", "Player Type");
If you wish to prompt the user for the Player arguments, you can read like so:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Player Name:");
String nickName = scanner.nextLine();
System.out.print("Enter Player Type:");
String playerType = scanner.nextLine();
Player player = new Player(nickName, playerType);

Clearly you are using 0-arg constructor, when you haven't got one: -
Player player = new Player();
Note that, when you provide a parameterized constructor in your class, the compiler will not add default constructor. You would have to add one 0-arg constructor manually, if you are using it.
So, either you can add one 0-arg constructor as such: -
public Player() {
this.nick = "";
this.type = "";
this.health = -1;
}
or, use the parameterized constructor to create the object.

When your class explicitly defines constructor, implicit no-arg constructor won't be created.
You have explicit constructor in your class
public Player(String nickName, String playerType)
{
nick = nickName;
type = playerType;
health = 100;
System.out.println("Welcome " + nick +" the " + type + ". I hope you are ready for an adventure!");
}
And trying to invoke no-arg constructor
Player player = new Player();
Either you need to pass parameters in above code (or) create no-arg constructor.

What you tried to do in your main()-method was to create a new Player object. But the problem is that you had to use the constructor you implemented (Player(String, String)) but you used a constructor without any parameters (Player()).
You should either use empty strings (e.g. if you want to get a player dummy)
Player player = new Player("","");
or you should give the new player instance the name and type you want to, so for example
Player player = new Player("flashdrive2049","Player");
Regards.

A default constructor is created by java when a construtor is missing, this construtor simply calls the super class. When you defined an explicit constructor java wont create one. So you can either define one default constructor in your class
e.g.
public Player()
{ nick = "abc";
type = "type";
health = 100;
System.out.println("Welcome " + nick +" the " + type + ". I hope you are ready for an adventure!");
}
or modify the code to call the constructor u defined.
Player player = new Player("nick","type");

Related

java println running function not returning function

FULL GITHUB FILES FOUND HERE
This is class Roulette.java
public static void main(String[] args) {
System.out.println("Welcome to roulette " + Casino.player());
}
This is class Casino.java
public static String player() {
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Please enter your name : ");
name = sc.nextLine();
return name;
}
When running Roulette.java it's not printing Casino.player() as a variable of your name, but running the function and asking for your name. I want to run Casino.java first,ask your name, then run roulette and welcome you with your name. NOT ASK YOUR NAME AGAIN.
Note: New to programming
The player() method in the Casino class prints out the message to input the users name. This will happen every time the method is called. To do what you want to do you need to create a conditional that checks if the player has already been set.
NOTE: This is not good practice or class design and in the future you should look into proper practice for class design and setting fields in a class. I would suggest posting this code on Code Review once you get it working to get a full answer on how this design can be improved.
Your Casino class should look something like this:
public class Casino {
private static String player = "";
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
this.player = sc.nextLine();;
}
return player;
}
}
Try something like this
String player = Casino.player();
System.out.println("Welcome to roulette " + player);

Creating Methods and Classes (Java)

I am trying to write a class called Student that is supposed to work with a StudentDriver. However, I am having a very hard time wrapping my head around the concept of methods and classes. I do not know how to receive and return data. Moreover, I don't even know if I am declaring my data correctly. Please help me. I would greatly appreciate it.
Also when I compiled the Student it says that it cannot find the symbol this.setGPA. How so? When in the driver it has .setGPA.
Thank you.
// This will be the "driver" class for the Student class created in
// MinilabWritingClasses (It looks very complicated because of all
// the comments, but it really just creates instances of Student and
// tells them to do things...)
public class StudentDriver
{
public static void main(String[ ] args)
{
//create an instance of Student
System.out.println("***** Creating a Student, calling the default constructor");
Student stud1 = new Student();
//print it so we can see what the default values were for the class data
//note that its toString() will be called automatically
System.out.println("\n***** printing it - notice the default values (set by Java)");
System.out.println(stud1);
//create another instance of a Student, passing in initial values to its constructor
System.out.println("\n***** Creating another Student, passing initial values to its constructor");
Student msBoss = new Student("Bill Gates", 56, 'm', 3.2, true);
//tell it to return its age
System.out.println("\n***** telling it to return its age.");
int theAge = msBoss.getAge();
System.out.println("Its age is: " + theAge);
//print it - note that its toString() will be called automatically;
System.out.println("\n***** printing it - see if values are correct");
System.out.println(msBoss);
//ask it if it is on probation
System.out.println("\n***** asking it if it is on probation (check answer)");
System.out.println("onProbation() returned: " + msBoss.onProbation());
//tell it to change its gpa to 1.3
System.out.println("\n***** telling it to change its gpa to 1.3");
msBoss.setGPA(1.3);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolean boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//tell it to complain
System.out.println("\n***** telling it to complain");
System.out.println("complain() returned: " + msBoss.complain());
//tell it to change its onScholarship field to false
System.out.println("\n***** telling it to change its onScholarship field to false");
msBoss.setOnScholarship(false);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//create a different student, tell it to have some different values, and tell it to print itself
System.out.println("\n***** creating a different Student, passing initial values to its constructor");
Student stud2;
stud2 = new Student("Hillary Clinton", 64, 'f', 2.0, true); //notice-can define variable and create it in 2 steps
//print it
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(stud2);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = stud2.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
}
}
Here is the class that I am writing.
public class Student
{
private String name;
private int age;
private char gender;
private double gpa;
private boolean onScholarship;
public Student()
{
}
public Student(String newName, int newAge, char newGender, double newGPA, boolean newScholarship)
{
this.name = newName;
this.age = newAge;
this.gender = newGender;
this.gpa = newGPA;
this.onScholarship = newScholarship;
}
public int getAge(int newAge)
{
return age;
}
public double setGPA (double newGPA)
{
this.setGPA = newGPA;
}
public boolean setOnScholarship (boolean newScholarship)
{
this.setOnScholarship = newScholarship;
}
public String toString()
{
return this.name + "\t" + this.age + "\t" + this.gender + "\t" + this.setGPA + "\t" + this.setOnScholarship;
}
public boolean onProbation()
{
if (onScholarship==true && gpa < 2.0)
return true;
else
return false;
}
}
Try to change this line:
this.setGPA = newGPA;
to this:
this.gpa = newGPA;
setGPA symbol not found is because there is no setGPA field (it is a method). You are trying to change the gpa field.
You also don't need the empty public Student() {} constructor -- this is automatically created by Java.
Also, as #Sam pointed out, since setOnScholarship() doesn't return anything, you can change the return type boolean to void. This is because there is no return statement, and this returning of nothing is a void type.
Overall, though, you have a good understanding on creating instances of another class (i.e., creating Students).
On request (although it doesn't have much to do with your code), here is a brief summary on static.
The static keyword is used with methods and fields that are not used with an instance of that class, but the class itself.
For example, in your case, pretty much all of the Student fields and methods are non-static, because they are properties of Student objects:
this.gpa;
this.setGpa();
On the other hand, if it were not changing a variable related to a single object, for example the total number of students, you could create a static field in Student:
public class Student {
// non-static fields for each instance
public double gpa;
// static field for the class
public static numStudents;
public Student() {
// create student by setting object (non-static) fields, for example...
this.gpa = 3.2;
// edit static variable
numStudents++; // notice how there is no `this` keyword - this changes a static variable
}
}
... and from StudentDriver, numStudents can be retreived with:
Student.numStudents; // notice how this is like `this.[property]`, but with the class name (Student) - it is an instance of the class
I hope this helps! OOP programming is a difficult topic that can't be explained so simply.

How to expand a randomHuman constructor to take two types of objects?

I am a java-noob as I recently started to learn in a course.
I have created a class:Humans which have ability to store their name and age, and also a subclass Students which extends Humans and adds the Year they began there studies.
I have constructed a randomHuman constructor where I call it(in my main class) and create a list with the humans(with random name and age).
My problem is when i want to random 5 human non-students and 5 students and create this list, I'm not sure how to find out what type of object is sent to the random constructor, so i know if i should give it a year or not. And what type to tell the constructor to return.
I am sorry that this turned into an essay, but if anyone would be so kind to help then I would greatly appreciate it.
TLDR; How to expand a randomHuman constructor to take two types of objects?
Here is my main class:
public class Main {
public static void main(String []args){
Human newHuman = new Human( 18, "Tommy");
System.out.println("Age: " + newHuman.getAge());
System.out.println("Name: " + newHuman.getName());
System.out.println(newHuman.toString());
Human putte = new Human (25,"Putte");
System.out.println(putte);
//Varför blir det så?
//kanske lokal variabel
//Array RandomHumans
System.out.println(" ");
System.out.println("Array Human");
ArrayList<Human> myAl = new ArrayList();
for(int i = 0; i<15; i++){
Human xx =Human.randomHuman();
myAl.add(xx);
}
//Array RandomFysiker
for(int j = 0; j<myAl.size(); j++){
Human var = myAl.get(j);
System.out.println(var.toString());
}
System.out.println(" ");
System.out.println("Array Fysiker");
ArrayList<Fysiker> myAl2 = new ArrayList();
//puts the Fysiker in an array
for(int i = 0; i<15; i++){
Fysiker xx =Fysiker.randomHuman();
myAl2.add(xx);
}
//prints teh array
for(int j = 0; j<myAl2.size(); j++){
Fysiker var = myAl2.get(j);
System.out.println(var.toString());
}
}
}
and my Human class:
public class Human {
public String name;
public int age;
Human(int ageIn, String nameIn){ //Constructor
age=ageIn;
name=nameIn;
}
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String toString(){
return "Name: " + getName() +"," + " Age: " + getAge();
}
//Random human
// Behöver ändra konstruktorn så att den kan kolla
// om objectet är Fysiker eller Human och sedan,
// Behandla dom olika
//Problem1: Hur kollar man? Föreslag if(obj instanceof Fysiker), men vad ska jag ha som obj
//Problem2: Vilken returtyp ska man då ha?
public static Human randomHuman(){
String[] anArrayOfStrings={"Tom", "Jon", "Chris","Julian","Roberto","Sam","Lisa","Roxanne","Rebecca","Anton","Johannes","Antonella","Bianca"};
int randomAge = (int) (100*Math.random());
String randomName = anArrayOfStrings[(int)(Math.random()*anArrayOfStrings.length)];
int RandomYear = (int) (Math.random()*(2013-1932) + 1932);
// if(xx instanceof Fysiker){
//
// }
return new Human(randomAge,randomName);
}
}
and the subclass Fysiker(aka student):
/**
*
* #author Julian
*/
public class Fysiker extends Human{
public int schoolYear;
public Fysiker(int startYear,int ageIn, String nameIn){
super(ageIn, nameIn);
if (age>15){
if (startYear>2013){
} else if (startYear<1932){
} else {
schoolYear = startYear;
}
} else {
}
}
public int getYear(){
return schoolYear;
}
public String toString(){
return super.toString() +","+" Startyear: " +getYear();
}
}
Actually, your randomHuman() method, as mentioned in the comments, is not a constructor at all. It's a static factory method, although I'm sure you're not aware of what that means as yet.
Basically, a constructor is not a method at all and doesn't have a return type. What a constructor does is provide an initialization for a new instance of the class, created by using new, although it can do things that don't strictly initiate the fields of that object.
A method, in contrast, can return something. And in your particular case, the last line actually tells you exactly what it returns - it's calling new for the class Human, so it will return an object of class Human, never a Student.
In fact, the class Human is not aware of the class Student. In principle, you could write a subclass for a class, years after the parent class has been written. Parent classes don't need to know about their descendents. They just decide what they allow those descendents to change and what they don't allow them to change.
You could, in theory, put a method in Human that creates a Student instance. But I'm pretty sure that's not needed in the current situation.
What you probably want to do is fill a list of humans outside the definition of either Human or Student. Filling a random list is probably not part of "being a human" or "being a student" is all about, so you should just do it in your Main class, calling new Human() or new Student() as you wish and filling them as appropriate. Since you know which new you called, you also know whether or not to use a random year.
You could do it in a static method in your Main class, to signify that this is something you do for testing, and not really part of the logic of either a Human or a Student.
As for being able to tell which object you now got from the list - you can do that with instanceof. But you'll also need to typecast it to Student if you want to access its getYear() method.
However - and this is the neat thing about polymorphism - if you just call the toString() method, and don't even check the type of the object, you'll get it with the year if it's really a Student object, and without it if it's a plain Human object.
Let's assume your teachers actually want you to extend the randomHuman method so that it sometimes gives Human instances, and sometimes Students. When it gives Student, it should of course provide it with a year.
As I said above, this is called Tight Coupling between parent and subclass, and is not recommended. If I wanted to build another human subclass, such as Politician, I'd have to call you and ask you to release a new version of Human that also sometimes gives random Politicians. So, under protest, I'll explain how to do it.
Your existing function is:
public static Human randomHuman(){
String[] anArrayOfStrings={"Tom", "Jon", "Chris","Julian","Roberto","Sam","Lisa","Roxanne","Rebecca","Anton","Johannes","Antonella","Bianca"};
int randomAge = (int) (100*Math.random());
String randomName = anArrayOfStrings[(int)(Math.random()*anArrayOfStrings.length)];
int RandomYear = (int) (Math.random()*(2013-1932) + 1932);
// if(xx instanceof Fysiker){
//
// }
return new Human(randomAge,randomName);
}
We change it like so:
public static Human randomHuman(){
String[] anArrayOfStrings={"Tom", "Jon", "Chris","Julian","Roberto","Sam","Lisa","Roxanne","Rebecca","Anton","Johannes","Antonella","Bianca"};
int randomAge = (int) (100*Math.random());
String randomName = anArrayOfStrings[(int)(Math.random()*anArrayOfStrings.length)];
Human result = null;
if ( Math.random() < 0.5 ) {
// With a probability of 50%, create a plain human
result = new Human( randomAge, randomName );
} else {
// Create a student. Start by calculating a random year.
int randomYear = (int) (Math.random()*(2013-1932) + 1932);
result = new Fysiker( randomYear, randomAge, randomName );
}
return result;
}
So, you decide that you want to make a plain human, and within the scope of that decision, you create it with new Human(...) and assign to the result variable.
If you decide to make a student, within the scope of that decision, you calculate a random year, and create it with new Fysiker(). You can assign it to the variable result because polymorphically, it's Human. But in reality, internally, it's a Student.
You return the result variable, which may contain either a Human or a Student at this point.
For determining what type the object instance is use either object instanceof class or object.getClass().equals(Clazz.getSimpleName())
For return type just use the superClass (or interface). You can always cast it to the child if needed.
If you want to create 5 class of each you need a boolean in the method declaration and call it 5 times each to be sure u will have 5 instances of each class.
public static Human randomHuman(boolean isHuman){
If this is not important u can add a random boolean and then call the constructor:
boolean isHuman = Math.random() < 0.5;
if(!isHuman){
int RandomYear = (int) (Math.random()*(2013-1932) + 1932);
// create student
} else {
// create human
}

<identifier> expected when creating an array?

I am writing an airline program that will allow the user to input names and meal choice for each seating section economy, business, and first. I am trying to save all the names and meals into an array. but I am getting a syntax error.
I get expected message when I implement my flyer array.
I have looked on stack overflow. From what I can tell it should be ok to initialize my array this way.
Thanks for any help.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Flyers
{
public Flyers()
{
}
public List<String> seat = new ArrayList<>();
int numberOfFlyers;
int numberOfMeals;
String name;
String meal;
String[][] flyer;
public void addEconomyFlyer()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of economy seats sold: ");
numberOfFlyers = in.nextInt();
flyer = new [numberOfFlyers][numberOfFlyers];
}
}
I want each [][] to have the same number of items that is equal to the number of people on the plane. Then I will add a nested for loop that will add a name for each of the flyers, and a meal choice. ultimately i need to be able to print out the array Name and their Meal choice.
Almost, the issue here is you haven't specified a type for the array.
flyer = new [numberOfFlyers][numberOfFlyers];
should probably be
flyer = new String[numberOfFlyers][numberOfFlyers];
However that doesn't make a lot sense. One solution is to use,
flyer = new String[numberOfFlyers][2];
where 0 is name and 1 is meal. But, really you should probably have a flyer POJO,
flyer = new Flyer[numberOfFlyers];
Where Flyer might look something like,
class Flyer {
Flyer(String name, String mealType) {
this.name = name;
this.mealType = mealType;
}
String name;
String mealType;
public String toString() {
return "Name: " + name + ", Meal: " + mealType;
}
}
Then you can create new Flyer(s) and call toString() in your loop. You might also choose to add getter and setter functions for name and mealType.
change :
flyer = new [numberOfFlyers][numberOfFlyers];
to:
flyer = new String[numberOfFlyers][numberOfFlyers];
Scanner class
Scan.scanner.scan
You need scan it!!!!
identifier = here
This trickes computer in think identifier there! YES! WORK!

One of my variables in one of my classes "cannot be resolved or is not a field"

Here's my class Person.java (simplified to remove text I think is unrelated to the problem):
public class Person {
int myIdNumber;
String myName;
String myBirthday;
String myType;
Person(String forTheName, int forTheId, String forTheBirthday, String forTheType){
this.myIdNumber = forTheId;
this.myName = forTheName;
this.myBirthday = forTheBirthday;
this.myType = forTheType;
}
}
And here's PersonAdd.java (likewise simplified):
import javax.swing.JOptionPane;
public class PersonAdd {
public static int numOfPeople = 0;
static String instruction = "Enter the person's ";
static String theName;
static String theBirthday;
static String theType;
static void entryText(){
numOfPeople++;
theName = JOptionPane.showInputDialog(null, instruction + "name.", "Add People", JOptionPane.QUESTION_MESSAGE);
theBirthday = JOptionPane.showInputDialog(null, instruction + "birthday.", "Add People", JOptionPane.QUESTION_MESSAGE);
theType = JOptionPane.showInputDialog(null, instruction + "type.", "Add People", JOptionPane.QUESTION_MESSAGE);
}
public static void main(String[] args) {
entryText();
Object person1 = new Person(theName, numOfPeople, theBirthday, theType);
entryText();
Object person2 = new Person(theName, numOfPeople, theBirthday, theType);
entryText();
Object person3 = new Person(theName, numOfPeople, theBirthday, theType);
String response = person1.myName;
JOptionPane.showMessageDialog(null, response);
}
}
The expected result is for the last dialog box to display the name given, but it's not working, although I believe it is storing the data entered correctly. The key problem is in the line
String response = person1.myName;
which cannot be resolved or is not a field. It also happens if I add a get method and use that instead of myName. Eclipse doesn't even seem to be able to see any of the objects of person1.
I'm sure this has to do with my failure to understand inheritance, or static/non-static, or something. (This class-and-object stuff is especially tricky for me to grasp; I think in "SQL mode" and want to be able to say something like "select-from-where".)
You've declared your variable as type Object which is the base type of every reference type, ie. it's the parent class of your Person class.
You can therefore only access fields and methods available through the Object type.
You'll need to declare your variable as type Person
Person person1 = new Person(...);
or cast the variable before you use it
String response = ((Person) person1).myName;
Also, be careful with your access modifiers.

Categories