illegal start of expression, coin flip java - java

public class Coin
{
/**
* Creates a new Coin object.
*/
public Coin()
{
private boolean headup;
public void flip ()
{
headup = Math.random() < 0.5;
}
public boolean isHeads()
{
return headup;
}
public String toString()
{
if (headup)
return "Heads";
else
return "Tails";
}
}
}
can someone tell me what did i do wrong for my code?

You've nested methods inside of a constructor, something not legal in Java.
Solution: get those methods out of the constructor and out on their own in the class.
public class Coin {
private boolean headup;
public Coin() {
}
public void flip() {
headup = Math.random() < 0.5;
}
public boolean isHeads() {
return headup;
}
public String toString() {
if (headup)
return "Heads";
else
return "Tails";
}
}

Related

Looking for an implementation of an abstract method

I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
gp1.agregar(v1);
//gp1.mostrar(v1);
gp1.agregar(v2);
System.out.println(gp1.check());
GrandPrix gp2 = new GrandPrix();
gp2.agregar(vt1);
gp2.agregar(vt2);
gp2.agregar(m2);
System.out.println(gp2.check());
GrandPrix gp3 = new GrandPrix();
gp3.agregar(vt1);
gp3.agregar(vt2);
gp3.agregar(m1);
System.out.println(gp3.check());
GrandPrix gp4 = new GrandPrix();
gp4.agregar(m1);
gp4.agregar(m2);
System.out.println(gp4.check());
This is the class that is using
import java.util.ArrayList;
public class GrandPrix extends Rally{
ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();
public void agregar(Vehiculo v) {
ve.add(v);
}
public void agregar(Carro c) {
ve.add(c);
}
public void agregar(Moto m) {
ve.add(m);
}
#Override
boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
return false;
}
}
This is the class where everything goes on
public class Vehiculo {
private String Nombre;
private double velocidad_max;
private int peso;
private int comb;
public Vehiculo() {
setNombre("Anónimo");
setVel(130);
setPeso(1000);
setComb(0);
}
public Vehiculo(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
}
double rendimiento() {
return velocidad_max/peso;
}
public boolean mejor(Vehiculo otroVehiculo) {
return rendimiento()>otroVehiculo.rendimiento();
}
public String toString() {
return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
}
/**************************************
---------SET And GET Nombre------------
***************************************/
public String getNombre() {
return Nombre;
}
public void setNombre(String nuevoNombre) {
this.Nombre=nuevoNombre;
}
/**************************************
---------SET And GET velocidad_max------------
***************************************/
public double getVel() {
return velocidad_max;
}
public void setVel(double nuevaVel) {
this.velocidad_max=nuevaVel;
}
/**************************************
---------SET And GET peso------------
***************************************/
public double getPeso() {
return peso;
}
public void setPeso(int nuevoPeso) {
this.peso=nuevoPeso;
}
/**************************************
---------SET And GET comb------------
***************************************/
public int getComb() {
return comb;
}
public void setComb(int comb) {
this.comb = comb;
}
boolean esDe2Ruedas() {
return false;
}
}
This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{
private boolean sidecar;
public Moto(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(false);
}
public Moto(String string, double d, int i, int j, boolean b) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(b);
esDe2Ruedas(false);
}
public String toString() {
String str = null;
if(isSidecar())
str =super.toString()+", Moto, con sidecar";
else
str =super.toString()+", Moto";
return str;
}
public boolean isSidecar() {
return sidecar;
}
public void setSidecar(boolean sidecar) {
this.sidecar = sidecar;
}
I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.

Is it possible to avoid duplicate code when implementing methods for two similar class?

I have two classes: Fish and Plant. They do not inherit from any classes.
But both of them have one method called isAlive() which have the same implementation details. Now I have a list of fish and another list of dog and I need to remove dead fish and dead dog. I want my method to have same name but it is not possible without adding additional field to method signature. Is it possible I do not need to write additional chunk of code which does the same as the last chunk of code?
Below is the code. For class Model, Fish and Plant are two data members and they are ArrayList of Fish and Plant objects.
Is there any way I can write only one method called count and I do not need to add additional field to my method signature or modify my return type?
public class Fish{
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Plant{
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Model{
private int countDeadFish() {
int totalCount = 0;
for(Fish aFish : this.fish) {
if(aFish.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
private int countDeadPlants() {
int totalCount = 0;
for(Plant plant : this.plants) {
if(plant.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
}
If you do not want to use inheritance, then you can use a common method:
public class AliveChecker {
public static boolean isAlive(int size) {
return size > 0;
}
}
public class Plant{
public boolean isAlive(){
return AliveChecker.isAlive(this.size);
}
}
public class Fish{
public boolean isAlive(){
return AliveChecker.isAlive(this.size);
}
}
Since Fishand Plant do not inherit from anything yet you can consider creating a superclass and extend from it:
public class LivingThing {
protected int size = 1;
public boolean isAlive() {
return size > 0;
}
}
public class Plant extends LivingThing {
}
public class Fish extends LivingThing {
}
This example uses inheritance to classify Plantand Fish into the superclass LivingThing. You can set the size for example in the constructor of the Plant or an instance method:
public class Plant extends LivingThing {
public Plant(int size){
this.size = size;
}
}
Your Model could then be:
public class Model{
private int countDeadFish() {
return countDead(this.fish);
}
private int countDeadPlants() {
return countDead(this.plants);
}
private int countDead(ArrayList<LivingThing> things) {
int totalCount = 0;
for(LivingThing thing: things) {
if(!thing.isAlive()) {
totalCount++;
}
}
return totalCount;
}
}
Use interface
public interface LiveObject {
boolean isAlive();
}
public class Fish implements LiveObject {
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Plant implements LiveObject {
public boolean isAlive(){
if(this.size > 0){
return true;
}
return false;
}
}
public class Model{
private int countDead(Collection<LiveObject> objects) {
int totalCount = 0;
for(LiveObject obj : objects) {
if(obj.isAlive() == false) {
totalCount += 1;
}
}
return totalCount;
}
private int countDeadFish() {
return countDead(this.fish);
}
}
Based on the comments it seems you can't modify Fish or Plant. Here's an approach to reduce duplication in countDead<Something> methods which does not require this.
Basically you want to count items in an array which satisfy certain criteria. With Java 8 you can capture this criteria in a predicate using lambdas or method references. You do not need inheritance or implementation of a certain interface for this.
private long countDeadFish() {
return countDeadItems(this.fish, Fish::isAlive);
}
private long countDeadPlants() {
return countDeadItems(this.plants, Plant::isAlive);
}
private <T> long countDeadItems(Collection<T> items, Predicate<? super T> isAlive) {
return items.stream().filter(isAlive.negate()).count();
}
You could create a utility method (in a utility class somewhere):
public final class Liveliness {
private Liveliness() {
}
public static boolean isAlive(final IntSupplier sizer) {
return sizer.getAsInt() > 0;
}
}
Your method then becomes:
public boolean isAlive(){
return Liveliness.isAlive(this::getSize);
}
Alternatively, use an interface Life:
public interface Life {
int getSize();
default boolean isAlive(){
return getSize() > 0;
}
}
This way, adding a getSize method and inheriting from Life will add the method.
Note, avoid the following antipattern:
if(test) {
return true;
} else {
return false;
}
Use return test.

Java: How to populate a variable in subclass?

So this is not a assignment but one of my lecture slide did not make it clear and when I try to code something similar myself, I run into a problem.
I can't figure out how to populate a variable that is in my subclass.
here's my test code thus far:
Implementation class:
import javax.swing.JOptionPane;
public class House {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int count = 0;
room[] r = new room[3];
int option = JOptionPane.showConfirmDialog(null, "type");
if(option==0){
r[count]=new type();
r[count].setSize(25);
r[count].setType("Bedroom");
}
else if(option==1){
r[count] = new room();
r[count].setSize(25);
}
JOptionPane.showMessageDialog(null, r[count].toString());
}
}
Superclass:
public class room {
double size;
public room(){
}
public room(double size){
this.size=size;
}
public double getSize(){return this.size;}
public boolean setSize(double size){
if(size<0.0){
return false;
}
else{
return true;
}
}
public String toString(){
return "Room size: " + this.size;
}
}
Subclass:
public class type extends room {
String type;
public type(){
}
public type (double size, String type){
super(size);
this.type=type;
}
public String getType(){return this.type;}
public boolean setType (String type){
if(type.equals("")){
return false;
}
else{
return true;
}
}
public String toString(){
return super.toString() + "Room Type: " + this.getType();
}
}
when i try to run the code, if I tried to insert data into setType() method in type class, it would give me an error. Can someone please tell me where I am messing up? Thanks!
Remember the original pointer:
if(option==0){
type t = new type();
t.setSize(25);
t.setType("Bedroom");
r[count]= t;
}
Alternatively you can cast to original type:
((type) r[count]).setType("Bedroom");

Usage of Boolean Variable in Constructor

I am studying these codes below got from a website (source: https://gist.github.com/allisons/842546). Can anyone please explain the usage of the variable __processCalled? I don't get why it is put in the constructor and how it affects the process method (in both subclass and super class). It seems to me that this boolean variable is assigned values but is not actually used (like in the if statement: if (__processCalled) {}).
Thank you so much for your help!
//Provided Code
public class Account {
public boolean __processCalled;
public Account(Client c) {
__processCalled = false;
}
public boolean process(Transaction t) {
__processCalled = true;
return t.value() > -100 && t.value() < 1000000;
}
public class Client {}
public class Transaction {
private int value;
public Transaction(int v) {
value = v;
}
public int value() {
return value;
}
}
}
//My Code
public class FilteredAccount extends Account{
private boolean __processCalled;
private int filteredCount;
private int transactionCount;
public FilteredAccount(Client c) {
super(c);
__processCalled = false;
filteredCount = 0;
transactionCount = 0;
}
public boolean process(Transaction t){
transactionCount++;
__processCalled = true;
if(t.value == 0){
filteredCount++;
return true;
}else{
return super.process(t);
}
}
public double percentFiltered(){
if(transactionCount == 0){
return 0.0;
}
return filteredCount/transactionCount *100;
}
}

Missing return statement method ReturnCopy

I've created this method and I'm unsure why it says there's a missing return statement. do I need to change the print to a return? (it's the method at the very bottom) I'm a bit of a Java beginner so any help will be appreciated!
public class Book {
private String title;
private String author;
private int copies;
private boolean borrowed;
public Book( String inAuthor, String inTitle, int inNumberOfCopies ) {
this.author = inAuthor;
this.title = inAuthor;
this.copies = inNumberOfCopies;
}
public void borrowed() {
borrowed = true;
}
public void rented() {
borrowed = true;
}
public void returned() {
borrowed = false;
}
public boolean isBorrowed() {
return borrowed;
}
public String getAuthor() {
return this.author;
}
public static String getTitle() {
return getTitle();
}
public int getTotalCopies() {
return this.copies;
}
public int getAvailableCopies() {
}
public void withdrawCopy() {
int found = 0;
for (Book b : Library.getListOfBooks()) {
if (b.getTitle().equals(title)) {
if (found == 0) {
found = 1;
}
if (!b.isBorrowed()) {
b.borrowed=true;
found = 2;
break;
}
if (found == 0) {
System.out.println("Sorry, this book is not in our catalog.");
} else if (found == 1) {
System.out.println("Sorry, this book is already borrowed.");
} else if (found == 2) {
System.out.println("You successfully borrowed " + title);
}
}
}
}
public String returnCopy() {
boolean found = false;
for (Book book : Library.getListOfBooks()) {
if (getTitle().equals(title) && book.isBorrowed()) {
book.returned();
found = true;
}
if (found) {
System.out.println("you successfully returned " + title);
}
}
}
}
public String returnCopy()
String after public means that this method will return a String.
Your public String returnCopy() is currently not returning anything.
If you don't want to return anything, you can use void like this:
public void returnCopy(){
// code
}
Same issue with public int getAvailableCopies(), this is supposed to return an int but you are not returning anything.
Be careful:
this method:
public static String getTitle() {
return getTitle();
}
is a recursive method without a base condition. This will cause an error and force your application to crash.
You've defined the method as returning a String but you don't return a value anywhere in the method body. Simplest fix is probably to change the return type to void...
public void returnCopy() {...
}
All the above answer are pointing to the same issue, you have defined methods that are breaking the contract about what they return..
In you code you have as well something like this:
public int getAvailableCopies() {
}
so you are telling the compiler, you have a method with the name getAvailableCopies, it takes no params and return an integer.
BUT if you don't return anything, then you are contradicting your own method, your own contract, this is an enough reason for a compiler to complain...
Conclusion:
keep in mind the information that defines the method.

Categories