"Cannot find symbol"-error with custom class - java

I have got this simple method written in a custom class Numbers.java:
public class Numbers {
public int add (int n,int m) {
int i = n + m;
return i;
}
}
But when I try to call this method in my main-class like so:
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
int i = add(4, 6);
}
I get an red error sign on the line number of int i = add(4, 6); saying:
cannot find symbol
symbol: method add(int,int)
location: class Main
Also, when I wrote the method in my custom class I got a yellow warning sign on the line number where I declared the method saying "Missing Javadoc". I did some googling on this and found out that you were supposed to add certain URL's to your Java Platform Manager under the tab Javadoc, but as far as I can see all of my URL's are in place. I include a picture of it down below:
I have no idea what is wrong, and I'm grateful for any help!

Your method btnAddActionPerformed is in class Main, and is trying to call a function add, which is in a different class. Try this:
public class Numbers {
public static int add (int n,int m) {
int i = n + m;
return i;
}
}
And:
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
int i = Numbers.add(4, 6);
}

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);
}
}

error calling class object? [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 6 years ago.
So I have created a ArrayList within a GrownUp class that then produces a for loop to call a method from within another class. When I'm trying to call the object of this new method, I am getting an error that it is not recognising the object. This is what the method looks like:
public void personShowering()
{
PowerShower callshower = new PowerShower(1,1,1,1);
if(people.size()>1)
callshower.shower(people.get(0));
}
}
Person
import java.util.ArrayList;
public abstract class Person
{
ArrayList<Person> people;
Person(int age, String name)
{
}
public void shower(Person x)
{
people.get(0).shower(//what goes here?);
}
}
Error:
method shwer() in class perosn cannot be applied to given types;
required: Person
found: no given types
The callshower should be refering to a class called PowerShower which has been created using PowerShower callshower = new PowerShower(1,1,1,1); so I'm confused as to why it's looking in the Person class? The PowerShower class is quite big but I will post it:
PowerShower
public class PowerShower extends Shower
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState()
{
if (varPass == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 1;
}
#Override
public void shower()
{
PowerShower shower = new PowerShower(1,1,1,1);
shower.timePasses();
}
#Override
public void timePasses()
{
if(varPass == isOff)
varPass = 0;
else
{
GasMeter.getInstance().incrementConsumed(waterUse);
GasMeter.getInstance().incrementConsumed(10);
int gasconsumed = GasMeter.getInstance().getGasUsed();
WaterMeter.getInstance().incrementConsumed(waterUse);
WaterMeter.getInstance().incrementConsumed(5);
int waterconsumed = WaterMeter.getInstance().getWaterUsed();
System.out.println("Power shower water consumption = " + waterconsumed);
System.out.println("Power shower gas consumption = " + gasconsumed);
}
}
PowerShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 0 * incrementTime;
this.gasUse = 10 * incrementTime; //10x1;
this.waterUse = 5 * incrementTime; //5x1;
this.timeOn = 15 * incrementTime;
}
}
I'm not too sure why i am getting this error because I have created a object of that class and called it but it doesn't seem to be recognizing that object? Any is would be great, thanks.
What you are trying to do is not possible. I don't know why you believe it could be possible. This is not how multiple-inheritance could look like which is not supported by Java except for interfaces and default methods. If it was possible it would rather look like this (WON'T COMPILE):
public class GrownUp extends Person, SuperShower
....
people.get(0).shower()
You can call a method of an object. What you can't do is this:
people.get(0).callshower
A Person probably has no method (or field) callshower. callshower is a variable containing an object. You can call the method shower on it if existing.
It seems that you want to put the person and to have a shower together. What you can do is:
Add a method shower to Person and call it: people.get(0).shower()
Change PowerShower.shower() to have a parameter Person and then do the following call: callshower.shower(people.get(0))

Debugger stopped on uncompilable source code.

I just learnt how to use Arrays i wrote this program in Java on Netbeans. It compiled with no errors but gave me a blank output my if was true but when it jumped to the else the output was ok
THIS IS MY JAVA CLASS
public class VacationScale {
public int[] vacationDays;
public int yearsOfService;
public void setVacationScale(){
vacationDays = new int[7];
vacationDays[0] = 10;
vacationDays[1] = 15;
vacationDays[2] = 15;
vacationDays[3] = 15;
vacationDays[4] = 20;
vacationDays[5] = 20;
vacationDays[6] = 25;
}
public void displayVacationDays(){
if (yearsOfService >= 0){
System.out.println("Vacation days: " + vacationDays[yearsOfService]);
}else {
System.out.println("invalid number of years");
}
}
}
AND THIS IS MY MAIN CLASS (TESTING)
public class VacationScaleTest {
public static void main(String[] args) {
VacationScale personOne;
personOne = new VacationScale();
personOne.yearsOfService = 2;
personOne.displayVacationDays();
}
}
BOTH IN THE SAME PROJECT
i tried debugging and got Debugger stopped on uncompilable source code at
System.out.println("Vacation days: " + vacationDays[yearsOfService]);
That's because you still haven't set the array vacationDays[] at the point you make the call to displayVacationDays().
Do the following - add this line before the line where you have personOne.displayVacationDays(),
personOne.setVacationScale();
// Now make the call to display vacation days
I got the same error message in a completely different constellation.
I'm using java fx
I googled for it and found no similar cases. After some tests, I found out that when creating a new PropertyValueFactory I got this nerving error message.
The line of code that caused the problem was:
TableColumn<Values, String> col = new TableColumn<>(val.getName());
col.setCellValueFactory(
new PropertyValueFactory<Values,String>("Value")
);
The class Values is a subclass and looks like this:
private class Values {
private final SimpleStringProperty vall;
public Values(String d) {
this.vall = new SimpleStringProperty(d);
}
public String getValue() {
return vall.get();
}
public void setValue(String value) {
vall.set(value);
}
}
Solution:
After a lot of checking, I found out that my Values class must be PUBLIC and not private.
public class Values {
...
}
I hope it can be useful for someone.

Java errors with creating function

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!");
}
}
}

Categories

Resources