Java errors with creating function - java

I have created a class which should create Swords, but I just get a bunch of errors...
package swords;
public class Sword {
public static void main(String [ ] args){
public int numberOfSwords=0;
public static void newSword(String nameSword, int damageSword){
numberOfSwords++;
}
}
}
I want to, when I type newSword(Overpowered Sword, 1000000), increase the int numberOfSwords by one, the actual creation of the sword will come later :D
But I get a lot of errors:
At package swords; - The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files.
At public class Sword { - Implicit super constructor Object() is undefined for default constructor. Must define an explicit constructor
At public static void main(String [ ] args){ - String cannot be resolved to a type
At public int numberOfSwords=0; - Illegal modifier for parameter numberOfSwords; only final is permitted
And the final error at public static void newSword(String nameSword, int damageSword){ - Multiple markers at this line
- Syntax error on token ",", ; expected
- Syntax error on token "(", ; expected
- void is an invalid type for the variable newSword
- String cannot be resolved to a type
- Syntax error on token ")", ; expected
I hope you can help me!
EDIT: I'm running Linux Mint, so I dont know if it could be something with my system, since I tried the given code, but get the same errors! I'm investigating now ^ ^
EDIT 2: I just ran a command which told me I didn't have a JDK installed, I think I found the problem :P I'll pay more attention to requirements in the future, sorry...
EDIT 3: Apparently I do have a JDK installed, so I dont know anymore what the problem is... Suggestions are highly appreciated!

Try this
in Sword.Java
public class Sword{
public Sword(string name, int damage){
this.name = name;
this.damage = damage;
++swordsCreated;
}
public string getName(){ return name; }
public int getDamage(){ return damage; }
private string name;
private int damage;
public static int getCountOfSwordsCreated(){ return countOfSwordsCreated; }
private static int countOfSwordsCreated;
}
in Game.java
public class Game{
public static void main(string [] args)
{
Sword mySword = new Sword("Overpowered Sword", 1000000);
System.out.println(mySword.getName());
}
}

Im not sure what you want, something like this?
package swords;
public class Sword {
public static int numberOfSwords = 0;
public static void main(String[] args) {
newSword("Overpowered Sword", 1000000);
}
public static void newSword(String nameSword, int damageSword) {
numberOfSwords++;
}
}

Perhaps this would help.
package swords;
class Sword {
private static int numberOfSwords = 0;
public static void main(String[] args) {
newSword("Overpowered Sword", 100);
}
public static void newSword(String nameSword, int damageSword) {
numberOfSwords++;
}
}
Note:
It is a good practice to keep variables private and functions public. So that the public functions are the only possible way to access the variables, ensuring security.
Ensure that you save the code as Sword.java in a folder swords

Make sure your JAVA_HOME/JDK refers to valid path. When valid java not found than it gives java.lang related errors.

There are mainly 2 problems with your code:
Firstly, you are trying to pass a long value to an integer parameter of your function.
Next, numberOfSwords is declared and initialized in main() method, so it's a local variable. You need to make it global in order to access it from your newSword() method.
The following code snippet works perfectly in my NetBeans IDE 7.3. I think this is going to work for you.
Happy coding!!! :) :)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sword;
/**
*
* #author Jack Sparrow
*/
public class Sword {
/**
* #param args the command line arguments
*
*/
public static void main(String[] args) {
// TODO code application logic here
newSword("Overpowered Sword",1000000);
}
public static void newSword(String nameSword, long damageSword)
{
int numberOfSwords = 0;
if ((nameSword == ("Overpowered Sword")) && (damageSword == 1000000))
{
numberOfSwords++;
System.out.println(numberOfSwords);
}
else
{
System.out.println("Error!");
}
}
}

Related

error: cannot find symbol and how to create and add objects to an arraylist

I'm attempting to create objects of my Profile class and store them in an arrayList created in a ProfileCollector class I created.
import java.util.ArrayList;
public class ProfileCollector
{
private ArrayList<Profile> profileList;
public ProfileCollector()
{
profileList = new ArrayList<Profile>();
//peopleList = new ArrayList<String>();
}
public void addProfile(String initName, int initKcalTotal, int initProteinTotal, int initFatTotal){
profileList.add(new Profile(initName, initKcalTotal, initProteinTotal, initFatTotal));
}
}
Here is my profile class:
import java.util.ArrayList;
public class Profile
{
private ArrayList<DailyIntake> nutritionalStats;
private String name;
private int kcalTotal;
private int proteinTotal;
private int fatTotal;
//These values represent nutritional requirements
public Profile(String initName, int initKcalTotal, int initProteinTotal, int initFatTotal)
{
name = initName;
kcalTotal = initKcalTotal;
proteinTotal = initProteinTotal;
fatTotal = initFatTotal;
}
public String getName(){
return name;
}
public int getKcalTotal(){
return kcalTotal;
}
public int getProteinTotal(){
return proteinTotal;
}
public int getFatTotal(){
return fatTotal;
}
}
Here are the parts of my main.java that are important
public static void main(String[] args) {
ProfileCollector profiles = new ProfileCollector();
//theres also a line that calls to a method which calls to another method with this line: profiles.addProfile(new Profile(name, optimumCalories, optimumProteins, optimumFats));
}
The error message is that the variable profiles is cannot be found. My question is also if I am correctly creating objects and adding them to an ArrayList. I didn't know if creating a class was the best way to go about this, but it was the way I've partial seen before. Anything helps.
Here is the error message:
error: cannot find symbol
profiles.addProfile(new Profile(name,
optimumCalories, optimumProteins, optimumFats));
^
symbol: variable profiles
location: class Main
You can add a method in the ProfileCollector class, that accepts an Profile instance instead of 4 parameters. With this class you should be able to be able to add a new profile to your list and you should also be able to add a profile by typing in the 4 parameters, that are required to create a new Profile instance.
import java.util.ArrayList;
public class ProfileCollector
{
private ArrayList<Profile> profileList;
public ProfileCollector()
{
profileList = new ArrayList<Profile>();
//peopleList = new ArrayList<String>();
}
public void addProfile(String initName, int initKcalTotal, int initProteinTotal, int initFatTotal){
profileList.add(new Profile(initName, initKcalTotal, initProteinTotal, initFatTotal));
}
public void addProfile(Profile profile) {
profileList.add(profile);
}
}
You need make sure to send by parameters the profiles variable to that function and then send it to the other function that you said it calls
profiles.addProfile(new Profile(name, optimumCalories, optimumProteins, optimumFats));
Also you are giving a variable type Profile to the addProfile ,maybe you need to send only the profile atributes
profiles.addProfile(name, optimumCalories, optimumProteins, optimumFats);
Or change the addProfile to have a Profile by parameters that is the best practice
public void addProfile(Profile profile) {
profileList.add(profile);
}
If this is not the answer could you add some code from that functions, if you don't want to share the code put ...
Both Answeres above are good.
It is a compilation error so you need to learn how to interpret IDE error messages from the compiler.
The problem is you are calling a method signature that does not exist.
Eather define the method
public void addProfile(Profile profile)
or call the existiong method:
profiles.addProfile("Profile1", 1650, 450, 350);
use "this" to refer to own properties in an Object.
public void addProfile(String initName, int initKcalTotal, int initProteinTotal, int initFatTotal){
this.profileList.add(new Profile(initName, initKcalTotal, initProteinTotal, initFatTotal));
}
Keep it up!

Multiple Markers at this line, Java constructor error (beginner level).

I just started to learn java and am not fimiliar with the language. this is an online assignment i am doing for fun and to get more fimiliar, and can't figure out the multiple errors i am getting with the constructor line. Please help
public class WhackAMole {
public static void main(String[] args) {
int score;
int molesLeft;
int attemptsLeft;
char [][]moleGrid=new char[10][10];
int numAttempts; //is this needed
int gridDimensions; // is this also needed
/*Multiple markers at this line
- Syntax error on token "int", delete this token
- Syntax error, insert ";" to complete Statement
- Syntax error on token "int", delete this token
- numAttempts cannot be resolved to a variable
- gridDimensions cannot be resolved to a variable
- Syntax error on token "int", delete this token
- The method WhackAMole(int, int) is undefined for the type
WhackAMole*/
WhackAMole(int numAttempts, int gridDimensions) {
this.numAttempts=numAttempts ; //error-cannot use this in static content
this.gridDimensions=gridDimensions ; // error-cannot use this in static content
}
}
}
Move your constructor out of main() method.
I reccomend you to do some basic beginner level java tutorial. You cannot put the constructor in another method (it's in the main method). Also to use this.numAttempts you need object Attributes. I tried to move the code-snippets to give it more sense:
public class WhackAMole {
// Those are attributes
private int score;
private int molesLeft;
private int attemptsLeft;
private char[][] moleGrid = new char[10][10];
private int numAttempts; // is this needed
private int gridDimensions; // is this also needed
// Constructor
public WhackAMole(int numAttempts, int gridDimensions) {
this.numAttempts = numAttempts;
this.gridDimensions = gridDimensions;
}
public void play() {
// Game logic here
}
/* This Method should propably be in another class */
public static void main(String[] args) {
final WhackAMole wham = new WhackAMole(42, 1234567);
wham.play();
}
}
You were definining method inside a method which is not allowed in java. Also, I have moved the attributes to class level.
Please use below code:
public class WhackAMole {
int score;
int molesLeft;
int attemptsLeft;
char[][] moleGrid = new char[10][10];
int numAttempts; //is this needed
int gridDimensions; // is this also needed
WhackAMole(final int numAttempts, final int gridDimensions) {
this.numAttempts = numAttempts; //error-cannot use this in static content
this.gridDimensions = gridDimensions; // error-cannot use this in static content
}
public static void main(final String[] args) {
WhackAMole whackAMole = new WhackAMole(30, 40);
System.out.println("numAttempts:" + whackAMole.numAttempts + " gridDimensions:" + whackAMole.gridDimensions);
}
}

How to set and get with three Classes?

I have a similar question on this topic but I dumbed it down and left out all the extra code. Also, I took the advice of the old question and set my variables to zero but it didn't make any difference.
Main:
public class WhyAPrints0Main {
public static void main(String[] args) {
int x = 24;
WhyAPrints0 set = new WhyAPrints0();
WhyAPrints01 get = new WhyAPrints01();
set.setWhy(x);
get.print();
}
}
Class 1
public class WhyAPrints0 {
private int why;
public int getWhy() {
return why;
}
public void setWhy(int why) {
this.why = why;
}
}
Class 2
public class WhyAPrints01 {
WhyAPrints0 get = new WhyAPrints0();
int a = 0;
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
I really don't understand why this doesn't print 24 so if someone could explain well and possibly fix the code to where it does I would really appreciate it.
Why would you expect it to print 24?
You invoke the print() method:
get.print();
Which prints 0:
public class WhyAPrints01 {
WhyAPrints0 get = new WhyAPrints0();
int a = 0;
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
(Since 0 is the default value for an int, which is what is returned by get.getWhy().)
I think your confusion is coming from the concept of having multiple instances of the same class. You have two different instances of WhyAPrints0. One in your main() method and one in your second class. These two instances have nothing to do with one another. Setting a value in one doesn't affect the other.
As an analogy, consider two identical cars. If you put something in the trunk of one car, you shouldn't expect to retrieve it from the trunk of the other car. It doesn't matter that the cars are otherwise identical, they're not the same car.
You have to link your WhyAPrints01 to your WhyAPrints0 some how. Right now you have 2 instances of WhyAPrints0. You can change your WhyAPrints01 to something like this so you can set an instance of WHyAPrints0 in your WhyAPrints01 class.
public class WhyAPrints01 {
WhyAPrints0 get;
int a = 0;
public WhyAPrints01(WhyAPrints0 get){
this.get = get;
}
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
And your main to:
public static void main(String[] args) {
int x = 24;
WhyAPrints0 set = new WhyAPrints0();
set.setWhy(x);
WhyAPrints01 get = new WhyAPrints01(set);
get.print();
}

Java Static constructor not working

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)

Using variables in a nested class JAVA

I am very new to programming and have a question about using variables in what I believe to be called "nested classes."
class BeginningGameTest {
int attack;
int defend;
public static class James
{
attack = 25;
defend = 15;
}
public static class Janet
{
attack = 45;
defend = 1;
}
public static class Jackson
{
attack = 10;
defend = 20;
}
public static void main(String[] args) {
System.out.prinln(James.attack);
}
}
Do I have the general idea down? I would like to save variables that are the "same" thing, but are different from class to class and are accessed differently like in the print line. I do get a few errors, what should I do to keep the same concept and still keep it fairly simple so I could understand it? Are there any easy to understand tutorials for people who are new to programming in general?
Thanks in advance!
The design of this seems incorrect.
What you're trying to go for when working in an object-oriented language is the basic model of something you wish to represent.
Those three static classes seem to represent the same type of object, so let's create a simple model for them. Think of models like a cookie-cutter. Every cookie cut with this will be the same generic "shape", but will have different characteristics about it (sprinkles, frosting beard, etc). This model should be in its own separate file.
public class Player {
private String name;
private int attack;
private int defense;
public Player(String theirName, int theirAttack, int theirDefense) {
name = theirName;
attack = theirAttack;
defense = theirDefense;
}
// create getters and setters for their attack and defense
}
To actually make use of it, you'd want to instantiate the object.
public class BeginningGameTest {
public static void main(String[] args) {
Player p1 = new Player("James", 25, 15);
Player p2 = new Player("Janet", 45, 1);
Player p3 = new Player("Jackson", 10, 20);
// interactions with the objects below
}
}
Some superb beginner resources already exist in the Java tag wiki; give those a thorough reading. Try new things out, and don't be afraid to ask (good) questions about things you don't understand.
You should create an inner class then define instances of that class within the main method.
public class BeginningGameTest {
public static void main(String[] args) {
Player james = new Player(25,15);
Player janet = new Player(45,1);
Player jackson = new Player(10,20);
System.out.println(james.getAttack());
}
}
class Player{
int attack;
int defend;
public Player(int attack, int defend){
this.attack = attack;
this.defend = defend;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefend() {
return defend;
}
public void setDefend(int defend) {
this.defend = defend;
}
}
You should use the concept of instances to distinguish persons, rather than defining a class for each person. You can define a single class "Person" and instantiate James, Jackson etc. To give them each different attack/defence values, you can use constructors with arguments.
I feel that you might benefit from reading an introduction to object oriented programming. Try searching for "object oriented programming".
You can go two ways about this. You could create subclasses such that James, Janet and Jackson are all classes of the same type, being BeginningGameTest. For example, James could be:
public class James extends BeginningGameTest
{
public James()
{
attack = 25;
defend = 15;
}
}
What I think you want James, Janet and Jackson to be, are not subclasses, but rather instances of the same class BeginningGameTest, like this:
BeginningGameTest James = new BeginningGameTest();
James.setAttack(25);
James.setDefend(15);
There are a few concepts you should read upon:
Classes vs instances
Inheritance
And I also implicitly introduced you to the concept of setters (and getters), typical for Java beans.
This will work:
public static class James
{
static int attack = 25;
static int defend = 15;
}
// ...
Then this would work:
public static void main(String[] args)
{
System.out.prinln(James.attack);
}
This is probably a better design:
public class Player()
{
public static enum NAME { JAMES, JANET };
int attack, defend;
public Player(NAME name)
{
switch (name)
{
case JAMES:
attack = 25;
defend = 15;
break;
// ...
}
}
public static void main(String[] args) throws Exception
{
System.out.println(new Player(NAME.JAMES).attack);
}
}
This is a better design for realistic requirements: (allowing run-time creation of players)
int attack, defend;
String name;
public Player(int attack1, int defend1, String name1)
{
attack = attack1;
defend = defend1;
name = name1;
}
What you can simply do is create different objects of your class that will hold different values of variables attack and defend. Here is the code for the same.
/* package whatever; // don't place package name! */
class Main
{
int attack,defend;
public Main(int attack,int defend)
{
this.attack=attack;
this.defend=defend;
}
public void show()
{
System.out.println("attack: "
+attack+" defend: "+defend);
}
public static void main (String[] args) throws java.lang.Exception
{
Ideone James = new Main(125,15);
James.show();
Ideone Janet = new Main(45,1);
Janet.show();
Ideone Jackson = new Main(10,20);
Jackson.show();
}
}

Categories

Resources