To my understanding of the error, the most common cause is because I haven't included "public static void main (String[] args)", but I've done this prior to discovering the error, which is leaving me stumped. Can anyone help me out?
import java.io.*;
class basketBall
{
private String name;
private double number;
private String team;
// declare getter method public
public String getName()
{
return name;
}
// declare setter method public
public void setName(String n)
{
name = n;
}
// declare getter method public
public String getTeam()
{
return team;
}
// declare setter method public
public void setTeam(String t)
{
team = t;
}
// declare getter method public
public double getNumber()
{
return number;
}
// declare setter method public
public void setNumber(double num)
{
number = num;
}
// declare dribble method
void dribble()
{
System.out.println (name + ", " + number + " dribbles down the court...");
}
// declare shoot method
void shoot()
{
System.out.println (name + " shoots... And he scores, for the " + team + "'s!");
}
}
// test class for basketBall class
class basketBallTester
{
public static void main (String[] args)
{
//construct player and fills in its objects
basketBall Player1 = new basketBall();
// fill in objects of player1
Player1.setName("Ethan");
Player1.setTeam("Vikings");
Player1.setNumber(15);
// call methods
Player1.dribble();
Player1.shoot();
}
}
You have several options to run your program this. One of them is:
Create a separate basketBallTester.java file, and place there your class basketBallTester.
Compile both files: basketBallTester.java and basketBall.java
Run your program with java basketBallTester
Related
The code is incomplete at the moment, but I was wondering if I could use the String partNo the one that the constructor is making inside the mutator.
public static class Invoice{
Scanner sam = new Scanner(System.in);
int Quality;
double price;
public Invoice(){
}
public Invoice(String partNo, String description) {
}
public void setPartNo() {
System.out.println("Enter part no: ");
String partNo = sam.nextLine();
}
public static String getPartNo() {
return Invoice.getPartNo();
}
}
public static void main(String[] args) {
Invoice.getPartNo();
public static class Invoice{
Scanner sam = new Scanner(System.in);
int Quality;
double price;
public Invoice(){
}
public Invoice(String partNo, String description) {
}
public void setPartNo() {
System.out.println("Enter part no: ");
String partNo = sam.nextLine();
}
public static String getPartNo() {
return Invoice.getPartNo();
}
}
public static void main(String[] args) {
Invoice.getPartNo();
You here have a few parameters to your constructor, you don't do anything with, which is pretty pointless. They won't exist anymore once the constructor has finished executing, so it's impossible for your mutators to get them
Those parameters, set them up as instance members, that way your mutators will also have access to them.
public static class Invoice {
Scanner sam = new Scanner(System.in);
int quality;
double price;
// add the additional instance members
String partNo;
String description;
public Invoice() { }
public Invoice(String partNo, String description) {
this.partNo = partNo;
this.description = description;
}
// a normal mutator (setter) will not use a Scanner, but accept the value as parameter
// but for now, I'm keeping your original design
public void setPartNo() {
System.out.println("Enter part no: ");
this.partNo = sam.nextLine();
// again, use this.partNo. If you declare it as a String here, it will no longer exist when the method is finished
}
// this getter is both pointless, and will cause trouble by creating an endless
// recursive loop. Delete it.
public static String getPartNo() {
return Invoice.getPartNo();
}
}
Now, the same code with some improvements:
public static class Invoice {
int quality;
double price;
// add the additional instance members
String partNo;
String description;
public Invoice() { }
public Invoice(String partNo, String description) {
this.partNo = partNo;
this.description = description;
}
public void setPartNo(String partNo) {
// you can always add validation on the new value here
this.partNo = partNo;
}
public String getPartNo() {
return partNo;
}
}
this, you will be able to use as follows:
public static void main(String[] args) {
Invoice in = new Invoice("part", "description");
System.out.pintln(in.getPartNo());
in.setPartNo("new PartNo");
System.out.println(in.getPartNo());
}
If you are wondering whether your getter should be static:
it should only be static if the field is static itself. Since you set the value by a parameter you pass to the constructor, it is doubtfull it should be static.
A parameter to the constructor should (usually) only set the value for that particular instance.
If it's a static field, it will be set for every single instance of that type.
I have a question about this code:
public class Musician {
private String name;
public String instrument;
public Musician(String name, String instrument){
this.name= name;
this.instrument= instrument;
}
public String getInstrument() {
return instrument;
}
public String getName() {
return name;
}
private String getClassName(){
return "Musician ";
}
public void play(){
System.out.println("[M] "+getClassName() + " plays music.");
}
public void printInfo(){
play();
System.out.println("[M] Class name: "+ getClassName());
System.out.println("[M] Instrument: "+ getInstrument());
}
}
public class RockMusician extends Musician{
public String instrument;
public RockMusician(String name, String instrument) {
super(name, instrument);
this.instrument= instrument + " and drums";
}
public String getClassName(){
return " RockMusician ";
}
public void play(){
System.out.println("[RM] "+ getClassName() + getName() + " breaks his "+ super.getInstrument() + "!");
}
}
public class IsraelyRockMusician extends RockMusician {
public IsraelyRockMusician(String name, String instrument) {
super(name, instrument);
}
public String getInstrument() {
return instrument;
}
public String getName(){
return super.getName() + " the king";
}
public String getClassName() {
return " IsraelyRockMusician ";
}
}
public class Testing {
public static void func(Musician m){
System.out.println("I've got a musician!");
}
public static void func(RockMusician m){
System.out.println("I've got a rock musician!");
}
public static void main(String[] args) {
Musician m3 = new IsraelyRockMusician("Chanoch", "guitar");
m3.printInfo();
}
}
I have IsraeliRockMusician who inherits RockMusician who Inherits Musician,
I then make a Musician m3 with the name "chanoch" and instrument "guitar"
and I active the method, print Info,
because the printInfo is in the father -> RockMusician which contains 3 methods on itself-> play(),getClassName(),and getInstrument(),
my question is, when the method showinfo runs, play is going all the way to the overwriten method and prints "[RM] IsraelyRockMusician Chanoch the king breaks his guitar!",
now this is fine, but the next line is "[M] Class name: Musician ", which means the getClassName was given "Musician" and Im asking why its not "IsraeliRockMusician" since the method was overwritten.
I'm sorry if the question is a bit hazey.
The problem is that the method of the base class has private access.
private String getClassName(){
return "Musician ";
}
Change it to public/protected so you can override it.
Instead of having a function where you hardcode the class name, you should use the following:
public class Foo {
public void printClassName() {
System.out.println(this.getClass().getName());
}
}
This way, if you change your class name, you don't need to update the method that you've written. One caveat to this is if you run an obfuscation tool against your code, the class name may be replaced with random characters. In that case, you can create a const string in your class and refer to that instead.
I have 3 classes; 1) Main 2) SettersAndGetters 3) AnotherClass.
In my main class, I set the setters. And I am looking for a way to access these values from AnotherClass. Right now I am getting a null which is due to the new instance I created. So how can I get round that, how to retrieve the value that I set in main.
public class Main{
public static void main(String args[]){
GettersAndSetters sg = new GettersAndSetters();
AnotherClass copyOfSG = new AnotherClass();
sg.setName("Mo");
sg.setAge(20);
sg.setIdNum("77777");
System.out.print("Name : " + sg.getName() + " Age : " + sg.getAge()+"\n");
System.out.println(copyOfSG.printout());
//In here I am trying to print the value that is
//in my 3rd class "AnotherClass" but i am getting null.
}
}
Output:
Name : Mo Age : 20
Age: 0
Name: null
SettersAndGetters:
public class GettersAndSetters{
private String name;
private String idNum;
private int age;
public int getAge(){
return age;
}
public String getName(){
return name;
}
public String getIdNum(){
return idNum;
}
public void setAge( int newAge){
age = newAge;
}
public void setName(String newName){
name = newName;
}
public void setIdNum( String newId){
idNum = newId;
}
}
AnotherClass:
public class AnotherClass {
public void printout() {
GettersAndSetters gs1 = new GettersAndSetters();
System.out.println("Age: " + gs1.getAge());
System.out.println("Name: " + gs1.getName());
System.out.println();
}
}
This occurs because you created two independent instances of GettersAndSetters in Main and in AnotherClass. Look:
public static void main(String args[]){
GettersAndSetters sg = new GettersAndSetters(); //first instance
AnotherClass copyOfSG = new AnotherClass();
...
}
public class AnotherClass {
public void printout() {
GettersAndSetters gs1 = new GettersAndSetters(); //second instance
...
}
}
And you're setting properties in first instance, but attempting to read it from second.
To solve just pass first instance from Main to method in AnotherClass as suggested by Satya.
public class AnotherClass {
public void printout(GettersAndSetters sg) {
System.out.println("Age: " + sg.getAge());
System.out.println("Name: " + sg.getName());
...
}
}
and call it next way:
public class Main{
public static void main(String args[]){
GettersAndSetters sg = new GettersAndSetters();
AnotherClass copyOfSG = new AnotherClass();
...
copyOfSG.printout(sg);
}
}
In my main class, I set the setters. And I am looking for a way to access these values from AnotherClass
Replace
System.out.println(copyOfSG.printout());
with
copyOfSG.printout(sg);
and your printout() method
public void printout(GettersAndSetters gs1) {
//No need of creating GettersAndSetters object
System.out.println("Age: " + gs1.getAge());
System.out.println("Name: " + gs1.getName());
}
there is one class BeanUtil in apache library.It will help you for this. this cass set and get attribute value.
BeanUtil.setProperty(<obje_name>, <field_name>, <field-value>);
BeanUtil.getProperty(<object_name>, <field_name>);
MyMath's constructor is supposed to call Homework's constructor, but super(); returns an error 'cannot find symbol'. It should not have any arguments.
Also, I am confused about how to call the method createAssignment using an arraylist, but I have to use it. Any advice?
Homework
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
public Homework(int pages, String hw) {
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath() {
super();
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
public class testHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
list.add(new MyMath(1));
list.add(new MyJava(1));
for (Homework s : list) {
s.createAssignment();
}
}
}
Compiler error:
Regarding the compiler error, you have to change the MyMath constractor to somthing like:
public MyMath() {
super(someInt, someString);
}
Or, you can add a non-arg constructor to the Homework class:
public Homework() {
this(someInt,someString);
}
You can learn about the super() keyword in the Javadocs tutoriel:
If a constructor does not explicitly invoke a superclass constructor,
the Java compiler automatically inserts a call to the no-argument
constructor of the superclass. If the super class does not have a
no-argument constructor, you will get a compile-time error. Object
does have such a constructor, so if Object is the only superclass,
there is no problem.
Code Suggestion:
As there is many other issues in your question, i modified all your classes like below:
Homework.java:
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
{
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public Homework(int pages, String hw) {
this.pagesToRead = pages;
this.typeHomework = hw;
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath.java
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath(int pages, String hw) {
super(pages,hw);
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
TestHomework.java:
class TestHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
// will create a homework with type Math and one page to read
list.add(new MyMath(1,"Math"));
// Assuming MyJava is similar to MyMath
list.add(new MyJava(1,"Java"));
for (Homework s : list) {
if (s instanceof MyMath) {
// modify the number of pages to read for the Math homework
s.createAssignment(3);
} else if (s instanceof MyJava) {
// modify the number of pages to read for the Java homework
s.createAssignment(5);
} else {
s.createAssignment(7);
}
}
}
}
In my main class, I have a static method which I pass the array into. It is a static method because if I want to pass something from the main class body to this method, it must be static. In a separate class I have a series of getters and setters (which must be non static ).
How can I pass my static array in and use the non-static getters and setters?
EDIT- In the arraySearch method...I cannot pass in the Person Array and access the getters in the Person Class
public class Main {
public static void main(String[] args) {
Person One = new Person("Alice","Foo", 22, false);
Person Two = new Person("Alice", "Foo",22, false);
Person Three = new Person("Bob","Bar",99, false);
Person Four = new Person("Joe","Blogs",64, false);
Person Five = new Person("Jane", "Joe",42, false);
Person [] People = {One,Two,Three,Four,Five};
printArray(People);
}
public static void printArray(Person [] People)
{
for(int i=0;i<People.length;i++)
{
System.out.println(People[i]);
}
}
public void arraySearch(Person [] People)
{
for(int i=0;i<People.length;i++) //Searches the Array of Objects
{
String firstName = Person.getFirstName();
String secondName=Person.getSecondName();
if((firstName.equals("Joe")&&secondName.equals("B" + //Searches for Joe Blogs and Jane Joe
"logs"))|| ((firstName.equals("Ja" +
"ne")&&secondName.equals("Joe"))))
{
int age=Person.getAge();
Person.setAge(age+1); //Increments Age by 1
}
}
}
}
public class Person {
private String mfirstName;
private String msecondName;
private int mage;
private boolean misRetired;
public Person(String firstName,String secondName,int age, boolean isRetired)
{
mfirstName=firstName;
msecondName=secondName;
mage=age;
misRetired=isRetired;
}
//GETTERS
public String getFirstName()
{
return mfirstName;
}
public String getSecondName()
{
return msecondName;
}
public int getAge()
{
return mage;
}
public boolean getRetired()
{
return misRetired;
}
//SETTERS
public void setFirstName(String firstName)
{
mfirstName=firstName;
}
public void setSecondName(String secondName)
{
msecondName=secondName;
}
public void setAge(int age)
{
mage=age;
}
public void setRetired(boolean isRetired)
{
misRetired=isRetired;
}
//STRING
public String toString()
{
return (mfirstName+"-"+msecondName+"-"+mage+"-"+misRetired);
}
}
This is very basic Java question. You need to create instance of object containing setter/getters from your static method. You can also pass static array in setter of this object. Then you should be able to call those getter/setter methods.
public class Main
{
public static void main(String[] args)
{
MyClass myclass = new MyClass();
myclass.setArgs(args);
System.out.println(myclass.getArgs());
}
}
public class MyClass
{
private String[] args;
public String[] getArgs()
{
return args;
}
public void setArgs(String[] args)
{
this.args= args;
}
}
You have to create an object instance from the class with the getters.
The Amit answer is correct; this just has some more info and more closely matches the situation you describe in your question.
Your basic premise "It is a static method because if I want to pass something from the main class body to this method, it must be static." is wrong. The method to which you pass the array does not need to be static. Here is some code:
public final class Main
{
private static final String[] staticOTron =
{
"one",
"two",
"three"
};
public static void main(final String[] args)
{
String[] hootBerrySause;
Tool tool = new Tool();
tool.setStaticOTron(staticOTron);
hootBerrySause = tool.getStaticOTron();
for (String value : hootBerrySause)
{
System.out.println("Value: " + value);
}
}
}
// this can be in a different file.
public final class Tool
{
private static String[] staticOTron;
public void setStaticOTron(final String[] newValue)
{
staticOTron = newValue;
}
public String[] getStaticOTron()
{
return staticOTron;
}
}
Sunil kumar from vmoksha
Your asking deeper navigation
Just create the instance of particular or create the getter &and setter in the main
class