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.
Related
I have the following code in my flink project:
public class Test {
public static void main(String[] args) throws Exception {
// set up the execution environment
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSet<Event> events =
env.readCsvFile(args[0]).pojoType(
Event.class,
"time",
"vid",
"speed",
"xWay",
"lane",
"dir",
"seg",
"pos"
);
System.out.println("----> " + events.count());
}
}
And this is the class Event:
class Event {
public int time;
public int vid;
public int speed;
public int xWay;
public int lane;
public int dir;
public int seg;
public int pos;
public Event() { }
public Event(int time_in, int vid_in, int speed_in, int xWay_in, int lane_in, int dir_in, int seg_in, int pos_in) {
this.time = time_in;
this.vid = vid_in;
this.speed = speed_in;
this.xWay = xWay_in;
this.lane = lane_in;
this.dir = dir_in;
this.seg = seg_in;
this.pos = pos_in;
}
}
The project compiles but when I run it, there is an error:
java.lang.ClassCastException: org.apache.flink.api.java.typeutils.GenericTypeInfo cannot be cast to org.apache.flink.api.java.typeutils.PojoTypeInfo
The CSV file has 8 integer values separated by a comma in each line.
The documentation has the following example:
DataSet<Person>> csvInput = env.readCsvFile("hdfs:///the/CSV/file")
.pojoType(Person.class, "name", "age", "zipcode");
I don't know if the POJO definition is wrong, surely it is. I achieved what I wanted using map and readTextFile but this could be more expensive.
The ClassCastException is a bug that will be fixed soon and replaced by a more meaningful exception. Event is a GenericType instead of a PojoType. I think the reason might be that Event is member class instead of a global accessible class. Adding the static modifier should solve the problem.
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))
I setup a test jar app to run for my other program I have been working on this for hours and i cant find a reason for why it returns null. Thanks for helping!
hashy.java
import java.util.HashMap;
public class hashy {
private static HashMap<String, Integer> targets = new HashMap<String, Integer>();
public static void main(String[] args) {
Hashymashy mash = new Hashymashy();
mash.hashyMash();
String name = "Bobby";
int num = 10;
targets.put(name, num);
if (targets.containsKey(name) == true) {
System.out.println("It contains a key!");
} else {
System.out.println("It does not contain a key!");
}
if (targets.containsValue(num) == true) {
System.out.println("It contains a value");
} else {
System.out.println("It does not contain a value!");
}
}
public HashMap<String,Integer> getTargets(){
return targets;
}
}
Hashymashy.java
public class Hashymashy {
public void hashyMash(){
hashy h = new hashy();
String name = "Bobby";
Integer fnum = h.getTargets().get(name);
System.out.println("Number is "+fnum+"!");
}
}
You are trying to retrieve the value associated with "Bobby" before adding it to the HashMap.
mash.hashyMash();
is called before targets.put(name, num);, so
Integer fnum = h.getTargets().get("Bobby");
will return null since there is no "Bobby" yet.
PS: seems like a bad design to me, since Hashymashy classes create instances of hashy classes & vice-versa.
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);
}
The goal is to produce this:
Picture of the task summary here
These are the errors I get when I try to compile:
screen shot
I have changed and fixed most of the more obvious errors I think which was mainly just stupid of me. Sorry.
I have this code
public class Ex5Program {
public void start() {
Tutor[] tutors = createTutorsArray();
printTutors(tutors);
printOnLeaveList(tutors);
updateTutorDetails(tutors[1]);
printNewTutorDetails(tutors[1]);
Tutor tutorWithMostPapers = getTutorWithMostPapers(tutors);
printTutorWithMostPapers(tutorWithMostPapers);
}
private Tutor[] createTutorsArray() {
String[] noPapers = {};
String[] introductoryPapers = {"CompSci101", "CompSci111"};
String[] coreStage1Papers = {"CompSci101", "CompSci105"};
String[] allStageOnePapers = {"CompSci111", "CompSci101", "CompSci105"};
String[] stageTwoPapers = {"CompSci210", "CompSci220", "CompSci225", "CompSci230"};
Tutor[] tutors = new Tutor[7];
tutors[5] = new Tutor("Sad Sack", 86302, introductoryPapers, false);
tutors[4] = new Tutor("Crystal Ball", 49123, introductoryPapers, false);
tutors[2] = new Tutor("Earl Lee Riser", 40879, allStageOnePapers, true);
tutors[3] = new Tutor("Tom Katt", 50876, stageTwoPapers, false);
tutors[1] = new Tutor("Candy Kane", 30869, noPapers, false);
tutors[0] = new Tutor("Carrie Oakey", 30987, coreStage1Papers, true);
tutors[6] = new Tutor("Sonny Day", 49586, stageTwoPapers, true);
return tutors;
}
private void printTutors(Tutor[] tutors) {
System.out.println("Current Tutors");
System.out.println("==============");
for (int i = 0; i < tutors.length; i++) {
System.out.print(i + 1 + ". ");
System.out.println(tutors[i].toString());
}
}
private void printOnLeaveList(Tutor[] tutors) {
System.out.println();
System.out.println("Tutors Currently on Leave");
System.out.println("=========================");
for (int i = 0; i < tutors.length; i++) {
if (tutors[i].isOnLeave()) {
System.out.println(tutors[i].getName());
}
}
}
private void updateTutorDetails(Tutor tutor) {
tutor.setName("Ali Katt");
tutor.setStaffId(23456);
String[] stage1Papers = {"CompSci101", "CompSci105", "CompSci111"};
tutor.setPapers(stage1Papers);
tutor.setOnLeave(true);
}
private void printNewTutorDetails(Tutor tutor) {
System.out.println();
System.out.println("Updated details");
System.out.println("===============");
System.out.println("Name: " + tutor.getName());
System.out.println("Id: " + tutor.getStaffId());
String[] papers = tutor.getPapers();
System.out.print("Papers: ");
if (papers.length > 0) {
for (int i = 0; i < papers.length; i++) {
System.out.print(papers[i] + " ");
}
} else {
System.out.print("None");
}
System.out.println();
if (tutor.isOnLeave()) {
System.out.println("Currently on leave");
}
}
private Tutor getTutorWithMostPapers(Tutor[] tutors) {
Tutor tutorWithMostPapersSoFar = tutors[0];
for (int i = 0; i < tutors.length; i++) {
if (tutors[i].teachesMorePapersThan(tutorWithMostPapersSoFar)) {
tutorWithMostPapersSoFar = tutors[i];
}
}
return tutorWithMostPapersSoFar;
}
private void printTutorWithMostPapers(Tutor tutorWithMostPapers) {
System.out.println();
System.out.println("Most papers");
System.out.println("===========");
System.out.println(tutorWithMostPapers.getName() + " teaches more papers than any other tutor.");
}
}
and I created this code here(It has been changed):
public class Tutor {
// instance variables
private String name;
private int staffId;
private String[] papers;
private boolean onLeave;
public Tutor(String name, int staffId, String[] papers, boolean onLeave) {
// Complete this constructor method
this.name = name;
this.staffId = staffId;
this.papers = papers;
this.onLeave = onLeave;
}
// Insert getName() method here
public String getName(){
return name;
}
// Insert setName() method here
public void setName(String name){
this.name = name;
}
// Insert getStaffId() method here
public int getStaff(){
return staffId;
}
// Insert setStaffId() method here
public void setStaffId(int StaffId){
this.staffId = staffId;
}
// Insert getPapers() method here;
public String[] getPapers(){
return papers;
}
// Insert setPapers() method here
public void setPapers(String[] papers){
this.papers = papers;
}
// Insert isOnLeave() method here
public boolean isOnLeave(){
return onLeave;
}
// Insert setOnLeave() method here
public void setOnLeave(boolean OnLeave){
this.onLeave = onLeave;
}
// Insert toString() method here
public String toString(){
return name + "(Staff id:"+staffId+")";
}
// Insert teachesMorePapersThan() method here
public Tutor teachesMorePapersThan(Tutor other){
return(papers.length>other.papers.length);
}
}
Typo: toString() not tostring(), which results in Object.toString() is being invoked and the intended formatted string is not being returned. Change to:
#Override public String toString()
Using the #Override annotation would have produced a compiler error in the case of tostring() being the method name and alerted you to the error, because no method of that name exists in a superclass.
Several of the setter methods have missing parameters:
// Insert setPapers() method here
public void setPapers(){
this.papers = papers;
}
// Insert setOnLeave() method here
public void setOnLeave(){
this.OnLeave = OnLeave;
}
First error: setStaffID()
You are calling it using an int, but on your method you say it doesn't have any parameter.
Take a look that you have some others errors caused by the same mistake. Correct them first...
You need to look at the error text to find the problems. While a newbie may instinctively just dismiss the error messages as uselesss (as a result of years of clicking the x or cancel or whatever on windows dialogues), The error text is actually the most useful resource for figuring out what the error is, 90% of the time.
For instance, the first error reads
File: F:\course related stuff\101\Lab06\Ex5\Ex5Program.java [line: 54]
Error: method setStaffId in class Tutor cannot be applied to given types;
required: no arguments
found: int
reason: actual and formal argument lists differ in length
If you read it carefully, you can see it tells you the name of the file, the line number, the method call name, the class name containing the method, and some additional information about the exact type of error. It is even telling you what you did wrong in calling the method, by putting an "int" where "no arguments" were required, that the "actual and formal argument lists differ in length".
Read the other error messages, and you will see that they actually tell you what the problem is.
This code also needs newlines inserted to group blocks of stuff, comments added to explain exactly how it works, and a few java style violations fixed - some teachers grade for style and clarity as well as just functionality.
Also, if the reason you are failing your class is because you don't understand how to program, it may be because of excessive use of stack overflow to solve the problems. In the real world, if you can just use somebody else's code, that's great, but the point of a programming class is is to teach you how to come up with your own code, not how to use somebody else's.
Well it's not easy to help, because i think you don't know what you are doing. But first thing when you create a set method like this:
public void setPapers(){
this.papers = papers;
}
you should declare the arguments like this:
public void setPapers(String[] papers){
this.papers = papers;
}
and you should know that variables names is caseSensitive so :
private boolean onLeave;
public boolean isOnLeave(){
//return OnLeave; this variable is not declared
return onLeave;
}
I think you need to study a little more, because you can't read the compilation errors.