How and why am I getting the compiler error ("class, interface, or enum expected")? Here is the code:
public class RolloverCounter{
private int counter=0;
private int max;
public RolloverCounter(int a){
if(a<0){
max = a;
}
}
public void increment()
{
for(int i=0;i<=max;i++)
{
counter++;
System.out.println(counter);
if(counter==max){
counter=0;
}
}
}
public void decrement(){
for(int i=0;i<=max;i++)
counter--;
if(counter<0)
{
counter=max;
}
System.out.println(counter);
}
public String toString() {
return counter;
}
public void reset(){
counter = 0;
}
}
}
What have I done wrong?
Your toString() method isn't returning a String,
public String toString() {
return counter;
}
should be something like
public String toString() {
return String.valueOf(counter);
}
Finally, you appear to have an extra closing brace (at the end) in your code as posted.
Related
**In this i am trying to sort an array of objects by their id's whose age > 30 but compiler is giving error in searchVoteByAge function in while loop :
while((j>-1)&& (v[j].getVoterId() > key.getVoterId())) in this line **
error :Exception in thread "main"
java.lang.NullPointerException at algorithms.Dijstra_algo.searchVoterByAge(Dijstra_algo.java:77) at
algorithms.Dijstra_algo.main(Dijstra_algo.java:55)
import java.util.Scanner;
public class Demo
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Voter voter[]=new Voter[4];
for(int i=0;i<voter.length;i++){
int v_id=sc.nextInt();
sc.nextLine();
String v_nme=sc.next();
sc.nextLine();
int v_age=sc.nextInt();
sc.nextLine();
boolean is_vote_casted=sc.nextBoolean();
sc.nextLine();
String constituency=sc.next();
sc.nextLine();
voter[i]=new Voter();
voter[i].setVoterId(v_id);
voter[i].setVoterName(v_nme);
voter[i].setVoterAge(v_age);
voter[i].setVoteCasted(is_vote_casted);
voter[i].setConstituency(constituency);
}
String cons=sc.next();
int c=findTotal(voter,cons);
if(c>0)
System.out.println(c);
else
System.out.println("No votes Casted");
Voter v[]=searchVoterByAge(voter);
if(v.length > 0){
for(Voter obj: v){
System.out.println(obj.getVoterId());
}
}
else
System.out.println("No such voters");
}
private static Voter[] searchVoterByAge(Voter[] voters) {
Voter v[]=new Voter[voters.length];
int k=0,f=0;
for(Voter obj:voters) {
if(obj.getVoterAge()<30) {
v[k]=new Voter();
v[k++]=obj;
f=1;
}
}
for(int i=1;i<v.length;i++) {
Voter key=v[i];
int j=i-1;
while((j>-1)&& (v[j].getVoterId() > key.getVoterId())) {
v[j+1]=v[j];
j--;
}
v[j+1]=key;
}
if(f == 0) {
return new Voter[0];
}
else
return v;
}
static int findTotal(Voter voters[],String s){
int c=0;
for(Voter voter:voters){
if(voter.isVoteCasted() && voter.getConstituency().equals(s)){
c++;
}
}
return c;
}
}
** Voter Class**
public class Voter {
private int voterId;
private String voterName;
private int voterAge;
private String constituency;
private boolean isVoteCasted;
public int getVoterId() {
return voterId;
}
public void setVoterId(int voterId) {
this.voterId = voterId;
}
public String getVoterName() {
return voterName;
}
public void setVoterName(String voterName) {
this.voterName = voterName;
}
public int getVoterAge() {
return voterAge;
}
public void setVoterAge(int voterAge) {
this.voterAge = voterAge;
}
public String getConstituency() {
return constituency;
}
public void setConstituency(String constituency) {
this.constituency = constituency;
}
public boolean isVoteCasted() {
return isVoteCasted;
}
public void setVoteCasted(boolean isVoteCasted) {
this.isVoteCasted = isVoteCasted;
}
}
I'm doing an assignment in which I have created an Appliance class that has a timePasses()method within it. This method re-directs some values that need to be stored within another method that is inside of another class. Here is where I am up to on this:
Appliance
public class ElectricCooker extends Cooker {
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;
}
}
#Override
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses() {
if (varPass == isOff) {
varPass = 0;
} else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter
public class ElectricMeter {
ElectricMeter() {
}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
System.out.println(value);
}
public int incrementGenerated() {
}
public boolean canGenerate() {
}
public String getConsumed() {
}
public String getGenerated() {
}
}
Main method
public class MainCoursework {
public static void main(String[] args) {
ElectricMeter a = new ElectricMeter();
a.incrementConsumed(//what goes here?);
}
}
So the value from timePasses()has been redirected into an ElectricMeter instance but now I need to return that value to the increentConsumed() method in the meter class and I'm stuck on how to do this. Since the value of electricityConsumed is 20, the output should be 20. But instead I have to pass a parameter into a.incrementConsumed(//pass parameter here) and what ever is passed gets printed out onto the screen instead of the 20 from electrictyUse. Any help on how to do this is appreciated, thanks.
Actually, the incrementConsumed method is indeed implemented as you described:
public void incrementConsumed(int value)
{
System.out.println(value);
}
A method called incrementXXX shouldn't really output anything, should it? It should increment a variable/field:
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
You should declare another method that returns electricityUsed:
public int getElectricityUsed() {
return electricityUsed;
}
Now let's fix your main method.
In your main method, you didn't even create anything that consumes electricity! How can the electric meter incrementConsumed? So remove everything from the main method and create a cooker:
// your constructor looks weird. So I passed in some random arguments..
ElectricCooker cooker = new ElectricCooker(20, 0, 0, 60);
Now call timePasses to simulate that some time passed:
cooker.timePasses();
And print the electricity used:
System.out.println(ElectricMeter.getInstance().getElectricityUsed());
you need to create an instance variable in ElectricMeter and update that value on say incrementConsumed. When you want to print that use accessor of this variable.
public class Electric {
public static void main(String[] args) {
ElectricCooker cooker = new ElectricCooker(1,2,3,4);
//opertion on cooker
//ignoring best way for singleton creation
int electricityUse = ElectricMeter.getInstance().getElectricityUse();
System.out.println(electricityUse);
}
}
class ElectricCooker // extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
public int electricityUse = -1;
public int currentState() {
if (varPass == 0)
return isOff;
else {
return isOn;
}
}
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
public void timePasses() {
if (varPass == isOff)
varPass = 0;
else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
this.electricityUse = 5 * incrementTime;
}
}
class ElectricMeter {
public int electricityUse = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
this.electricityUse = value;
}
public int getElectricityUse() {
return electricityUse;
}
}
In ElectricMeter, some operations don't perform what they should.
ElectricMeter.getInstance().incrementConsumed(electricityUse);
should increment something but it writes only in the output:
public void incrementConsumed(int value){
System.out.println(value);
}
You should write it rather :
public void incrementConsumed(int value){
consumed+=value;
}
and add a private int consumed field in ElectricMeter class to store the actual consumed.
And your getConsumed() which has a empty implementation :
public String getConsumed(){
}
should simply return the consumed field and you should return a int value and not a String.
public int getConsumed() {
return consumed;
}
In this way, you can do :
public static void main(String[] args){
ElectricMeter.getInstance().incrementConsumed(20);
int consumed = ElectricMeter.getInstance().getConsumed();
}
I have written the code:
public int compareTo(Object w) {
//w = (Word)w
if(this.count > (Word) w.getCount()) {
return -1;
} else if (this.count < (Word) w.getCount()) {
return 1;
} else {
return 0;
}
}
I have written the class Word. It implements Comparable so I must use the Object parameter for the compareTo() method.
However, I need the object to use a method in the Word class. I get an error if I cast and was wondering if I am doing something wrong or if I need to try something else?
Word class:
package comp10152_lab3;
public class Word implements Comparable{
private int count;
private String word;
public Word(String word) {
this.word = word;
this.count = 1;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
#Override
public int compareTo(Object w) {
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
public void countUp() {
count++;
}
#Override
public String toString() {
return word + "(" + count + ")";
}
#Override
public boolean equals(Object w) {
return w.equals(word);
}
}
The equals class is suppose to be that way, as per instruction.
The error I am getting is on the w.getCount() which is a "missing symbol" error.
This is the code that you need:
public int compareTo(Object o) {
Word w = (Word) o;
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
The problem that you were having was due to the fact that w was of the type Object, the statement w = (Word) w would not do what you wanted. The second part of the problem has to do with the precedence of the cast operator in Java. When you do (Word)w.getCount(), the getCount() part gets evaluated first, meaning that you were effectively doing (Word) <some int>. What you could have done was wrap it in parentheses like ((Word) w).getCount() to solve that problem.
You should implement Comparable<Word> so that the compareTo method is public int compareTo(Word w). Also you can simplify your compareTo code:
public class Word implements Comparable<Word> {
private int count;
public int compareTo(Word w) {
return w.count - this.count;
}
}
If you can't use java generics then you can still do your compareTo in one line:
public int compareTo(Object w) {
return ((Word) w).count - this.count;
}
How to implement the comparable and equals method in this Tree Map,so that my Contains Value return true.
How to do it?
How to implement?
import java.util.*;
class a
{
public static void main(String arr[])
{
TreeMap<String,Emp> map=new TreeMap<String,Emp>();
map.put("HEllo",new Emp("ada",23));
map.put("aehqn",new Emp("rewr",343));
map.put("rffewrf",new Emp("saerfwe",893743));
Set<Map.Entry<String,Emp>> x=map.entrySet();
Iterator<Map.Entry<String,Emp>> itr =x.iterator();
while(itr.hasNext())
{
Map.Entry<String,Emp> m=itr.next();
System.out.println(m.getKey());
Emp e=m.getValue();
e.display();
System.out.println();
}
System.out.println("NOw the value we will finid is"+map.containsValue(new Emp("ada",23)));
}
}
class Emp
{
String n;
int i;
public Emp(String n,int i)
{
this.n=n;
this.i=i;
}
public void display()
{
System.out.println("there are string "+n+" int"+i);
}
}
Thanks in advance
Your Code will look like
class Emp implements Comparable<Emp>
{
String n;
int i;
public Emp(String n,int i)
{
this.n=n;
this.i=i;
}
public void display()
{
System.out.println("there are string "+n+" int"+i);
}
public boolean equals(Object o){
if(o instanceof Emp){
Emp d = (Emp)o;
return ((d.n.equals(n)) && (d.i==i));
}
return false;
}
public int hashCode(){
return i/2 + 17;
}
public int compareTo(Emp d){
if(this.i>d.i)
return 1;
else if(this.i<d.i)
return -1;
return this.n.compareTo(d.n);
}
}
Please Ignore if any syntax error and you can improve method implementations also.
The containsValue() method of the Map interface uses the equals() method of the Object class.so in your case you have to override the equals() method and when you override the equals() method it is advised to override the hashCode() method too.
Below is the correct code:-
public class a
{
public static void main(String arr[])
{
TreeMap<String,Emp> map=new TreeMap<String,Emp>();
map.put("HEllo",new Emp("ada",23));
map.put("aehqn",new Emp("rewr",343));
map.put("rffewrf",new Emp("saerfwe",893743));
Set<Map.Entry<String,Emp>> x=map.entrySet();
Iterator<Map.Entry<String,Emp>> itr =x.iterator();
while(itr.hasNext())
{
Map.Entry<String,Emp> m=itr.next();
System.out.println(m.getKey());
Emp e=m.getValue();
e.display();
}
System.out.println("Now the value we will find is"+map.containsValue(new Emp("ada",23)));
}
}
class Emp
{
String n;
int i;
public Emp(String n,int i)
{
this.n=n;
this.i=i;
}
public void display()
{
System.out.println("there are string "+n+" int"+i);
}
#Override
public boolean equals(Object obj) {
if(obj==null)
{
return false;
}
if(this.getClass().equals(obj.getClass()))
return true;
else
return false;
}
#Override
public int hashCode() {
return super.hashCode();
}
}
Suppose I have a Enum defined something like this:
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getValue()),
B(AClass.getValue()),
C(AClass.getValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
I can pull out values using Sample.A or Sample.A.getAVal() without issue.
Now suppose that AClass.getValue() could take a parameter to return a possibly different particular value, eg AClass.getValue(42).
It is possible to pass arguments to a public Enum method and retrive the Enum values? In other words, could I have an Enum definition like
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getAValue()),
B(AClass.getBValue()),
C(AClass.getCValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public int getVal(int a){
// somehow pull out AClass.getAValue(a)
}
using Sample.A.getValue(42)?
You can do it, but only by making an abstract method in the enum, and overriding it in each value:
public enum Sample {
A(AClass.getAValue()) {
#Override public int getVal(int x) {
return AClass.getAValue(x);
}
},
B(BClass.getAValue()) {
#Override public int getVal(int x) {
return BClass.getBValue(x);
}
},
C(CClass.getAValue()) {
#Override public int getVal(int x) {
return CClass.getCValue(x);
}
};
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public abstract int getVal(int x);
}
Of course if you could create an instance of some other base type which has a getValue(int x) method, then you could put the code into the enum class itself instead of into the nested ones.
As stated in Java Specification
there is only one instance of each enum constant
So no, you can't have different values of a specific enum constant.
But you could put an array or a map inside your enum, so Sample.A.getValue(42) would return Sample.A.myMap.get(42) :
public enum Sample{
A(),
B(),
C();
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
public int getVal(int i){
return myMap.get(i);
}
public int setVal(int i, int v){
return myMap.put(i, v);
}
}
public class App {
public static void main(String[] args) {
Fruit.setCounter(5);
System.out.println(Fruit.Apple.getCmd());
Fruit.setCounter(6);
System.out.println(Fruit.Apple.getCmd());
}
}
public enum Fruit {
Apple {
public String getCmd() {
return counter + " apples";
}
},
Banana {
public String getCmd() {
return counter + " bananas";
}
};
private static int counter = 0;
public abstract String getCmd();
public static void setCounter(int c) {
counter = c;
}
}
Output:
5 apples
6 apples