Writing a contains method in java - java

package homework1;
//author Kyle Fields
public class HomeWork1{
public static void main(String[] args) {
int [ ] input = { 100, 37, 49 };
boolean result1 = contains( input, new Prime( ) );
boolean result2 = contains( input, new PerfectSquare( ) );
boolean result3 = contains( input, new Negative( ) );
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
static boolean contains(int[] array, Condition condition) {
return (condition(array));
}
}
package homework1;
/**
*
* #author Kyle Fields
*/
public interface Condition {
boolean makeYourCondition(int[] input);
}
package homework1;
/**
*
* #author Kyle Fields
*/
public class Prime implements Condition {
#Override
public boolean makeYourCondition(int[] input) {
for (int n : input) {
if (n >= 2) {
if (n == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (!(n % i == 0)) {
return true;
}
}
}
}
return false;
}
}
other classes below
package homework1;
/**
*
* #author Kyle Fields
*/
public class PerfectSquare implements Condition {
#Override
public boolean makeYourCondition(int[] input) {
for (int i : input) {
//takes the square root
long SquareRoot = (long) Math.sqrt(i);
//multiplys the sqrt by the sqrt to see if it equals the original
if (((SquareRoot * SquareRoot) == i) == true){
return true;
}
}
return false;
}
}
package homework1;
/**
*
* #author Kyle Fields
*/
public class Negative implements Condition {
boolean Negative(int n){
if (n <= -1){
return true;
}
return false;
}
#Override
public boolean makeYourCondition(int[] input) {
for (int i : input) {
if(i<0) return true;
}
return false;
}
}
my question is this, how do I finish this code? meaning: what do I need to do for my contains method? (currently, it is telling me the method condition(int[]) is not a valid method in the homework1 class.)

dummy code is fine as long as you know what you're doing.
First the contains() method, it takes an array and a Condition and returns a boolean. Let's write the signature
boolean contains(int[] array, Condition condition)
Prime, PerfectSquare, and Negative will be implementations of Condition, i.e.
interface Condition {
...
}
class Prime implements Condition {
...
}
class PerfectSquare ...
The setup of the exercise hints that in the Condition implementations you should check whether the argument int value satisfies the particular case; the contains() method iterates through the array and returns if it encounters a "true" or "false" if exhausts the list.

You can write the code as follow, using the contract of an interface to do the job, look after methods that attend your condition.
public class HomeWork {
public static void main(String[] args) {
int[] arr=new int[] {100, 37, 49};
Condition[] conditions= new Condition[]{
new Negative(),
new Prime(),
new PerfectSquare()
};
for (Condition condition : conditions) {
System.out.println(condition.makeYourCondition(arr));
}
}
}
interface Condition {
boolean makeYourCondition(int[] input);
}
class Negative implements Condition {
#Override
public boolean makeYourCondition(int[] input) {
for (int i : input) {
if(i<0) return true;
}
return false;
}
}
class Prime implements Condition {
#Override
public boolean makeYourCondition(int[] input) {
//TODO PUT YOUR CONDITION
return false;
}
}
class PerfectSquare implements Condition {
#Override
public boolean makeYourCondition(int[] input) {
//TODO PUT YOUR CONDITION
return false;
}
}

Related

Why does the counter inside if statement not work?

Hello friends I am trying to build a class Car for a project. There are many methods inside the following code as well as an if statement that I am having trouble building, consider the following code
public class Car extends Vehicle {
private boolean isDriving;
private final int horsepower;
private boolean needsMaintenance = false;
private int tripsSinceMaintenance = 0;
Car() {
super();
this.horsepower = 0;
this.isDriving = false;
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
public int getHorsepower() {
return this.horsepower;
}
public boolean getDrive() {
return this.isDriving;
}
public boolean getMain() {
return this.needsMaintenance;
}
public int getTRIP() {
return this.tripsSinceMaintenance;
}
public void drive() {
this.isDriving = true;
}
public void stop() {
this.isDriving = false;
}
public void repair() {
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
/**
* #param args
*/
public static void main(String[] args) {
Car auto = new Car();
auto.drive();
auto.stop();
if (auto.isDriving == true) {
if (auto.isDriving == false)
auto.tripsSinceMaintenance = auto.tripsSinceMaintenance + 1;
}
if (auto.tripsSinceMaintenance > 100)
auto.needsMaintenance = true;
System.out.println("Drive: " + auto.getDrive());
System.out.println("trip: " + auto.getTRIP());
}
}
What I want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenanceis greater than 100,needsMaintenanceshould becometrue`.
here I expected trips to be 1 but the result is the following:
Drive: false
trip: 0
I have tried this.isDriving==true; and basicaly wherever auto is inside the if statement I put this but the following error appears
non static variable cannot be referenced from static context
help me please!
What i want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenance is greater than 100 needsMaintenance should become true
Do this inside stop() method
fun stop() {
if (isDriving) {
tripsSinceMaintenance++;
}
if (tripsSinceMaintenance > 100) {
needsMaintenance = true;
}
isDriving = false;
}
You don't need to put == true inside of an if statement, it's doing that already,
if(someCondition) { // <-- this executes if the condition is true.
Also, you have conflicting conditions nested, meaning...
if (thisIsTrue) {
if (!thisIsTrue) {
// <--- unreachable statements
where you should be incrementing your variable is where you're setting "isDriving = true"
So your code would look like this:
public void drive() {
this.isDriving=true;
auto.tripsSinceMaintenance++;
}

calling boolean method, heads or tails

I'm wrote a method to simulate a coin toss, however, I do not know how to call this method in the main. Tips would really be appreciated!
(Here is the method, I didn't post the entire code because there are 8 other methods in this code).
public static boolean headsOrTails()
{
boolean coinState;
if (Math.random() < 0.5) {//heads 50% of the time
coinState = true; //heads
}
else {
coinState = false; //tails
}
return coinState;
}
You should call like :
public class Abc {
public static void main(String[] args) {
System.out.println(headsOrTails());
}
public static boolean headsOrTails() {
boolean coinState;
if (Math.random() < 0.5) {//heads 50% of the time
coinState = true; //heads
} else {
coinState = false; //tails
}
return coinState;
}
}
and it will print the output of the function as true or false.
Try this:
boolean isHead = headsOrTails();
if(isHead){
System.out.println("Heads");
}else{
System.out.println("Tails");
}
if value of isHead is true you have a Head :)
You can also improve readability of your code by shortening the boolean evaluation (like Boann mentioned):
public class CoinToss {
public static void main(String[] args) {
headsOrTails();
}
public static boolean headsOrTails() {
return Math.random() < 0.5;
}
}

illegal start of expression, coin flip 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";
}
}

Polymorphism and pre validating class attributes

Basically I have been tasked with tackling the following scenario:
When you are designing your class/es, you have to decide what attributes and methods you will include in. For example, if you decide to work in millimeters, your size variable (length) could be of type integer (but later, when calculating the cost, you will have to convert the volume into square inches, because the cost is given per cubic inch of plastic (Table 2 and Table 3 of the coursework)). The volume of plastic material used will be the difference between the outer and inner volume of a pipe. If you decided to prompt the length in meters, then the type should be double, or float, etc.
Once you have validated the user order, your program should determine, based on Table 1, what is the type of the ordered pipe.
Table 1. Types of plastic pipes available.
Type Plastic’s grade Colour print Inner insulation Outer reinforcement Chemical resistance
0 1 2
I 1 – 3 YES NO NO NO NO YES/NO
II 2 – 4 NO YES NO NO NO YES/NO
III 2 – 5 NO NO YES NO NO YES/NO
IV 2 – 5 NO NO YES YES NO YES/NO
V 3 – 5 NO NO YES YES YES YES/NO
That's all fine but the part that is getting me is this bit here:
Say in your main class you have determined that client’s order is a pipe of type I, then you can create an object of TypeI and for this object you can call the cost() method to calculate the cost and to show it to the user.
It is basically asking to not instantiate any objects before figuring out which one you need to instantiate, which is hard when it classes a big if statement in the verification as a 'Brute force method'.
Here is what I have so far.
Main
public class Cw1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Pipe> pipeList = new ArrayList<Pipe>();
// TODO code application logic here
Grade g1 = new Grade(1,3,true,false,false,false,false);
Grade g2 = new Grade(2,4,false,true,false,false,false);
Grade g3 = new Grade(2,5,false,false,true,false,false);
Grade g4 = new Grade(2,5,false,false,true,true,false);
Grade g5 = new Grade(3,5,false,false,true,true,true);
pipeList.add(g1);
pipeList.add(g2);
pipeList.add(g3);
pipeList.add(g4);
pipeList.add(g5);
for (Pipe p: pipeList)
{
p.setGrade(1);
p.setColour0(false);
p.setColour1(false);
p.setColour2(true);
p.setIns(true);
p.setReinf(true);
p.validate();
}
}
}
Grade (It must have abstracting in the solution)
public class Grade extends Pipe {
public Grade(int minGrade, int maxGrade, boolean hasColour0, boolean hasColour1, boolean hasColour2, boolean hasIns, boolean hasReinf) {
super(minGrade, maxGrade, hasColour0, hasColour1, hasColour2, hasIns, hasReinf);
}
}
And pipe
public abstract class Pipe {
public boolean isChemRes() {
return chemRes;
}
public void setChemRes(boolean chemRes) {
this.chemRes = chemRes;
}
public boolean isColour0() {
return colour0;
}
public void setColour0(boolean colour0) {
this.colour0 = colour0;
}
public boolean isColour1() {
return colour1;
}
public void setColour1(boolean colour1) {
this.colour1 = colour1;
}
public boolean isColour2() {
return colour2;
}
public void setColour2(boolean colour2) {
this.colour2 = colour2;
}
public double getDiameter() {
return diameter;
}
public void setDiameter(double diameter) {
this.diameter = diameter;
}
public boolean isIns() {
return ins;
}
public void setIns(boolean ins) {
this.ins = ins;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public boolean isReinf() {
return reinf;
}
public void setReinf(boolean reinf) {
this.reinf = reinf;
}
public Pipe(int minGrade, int maxGrade, boolean hasColour0, boolean hasColour1, boolean hasColour2, boolean hasIns, boolean hasReinf) {
this.minGrade = minGrade;
this.maxGrade = maxGrade;
this.hasColour0 = hasColour0;
this.hasColour1 = hasColour1;
this.hasColour2 = hasColour2;
this.hasIns = hasIns;
this.hasReinf = hasReinf;
}
public Pipe() {
}
//<editor-fold desc="Class variables">
private int grade;
private double length, diameter;
private boolean colour0, colour1, colour2, ins, reinf, chemRes;
private int minGrade, maxGrade;
private boolean hasColour0, hasColour1, hasColour2, hasIns, hasReinf;
// </editor-fold>
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
//<editor-fold desc="Public Methods">
public double calcVol()
{
return 0;
}
public double calcCost()
{
return 0;
}
public void validate()
{
if ((grade >= minGrade && grade <= maxGrade) & (colour0 == true && hasColour0 || colour1 == true && hasColour1 || colour2 == true && hasColour2) && (ins == hasIns) && (reinf == hasReinf))
{
System.out.print("True");
}
else
{
System.out.print("False");
}
}
// </editor-fold>
}
So basically, I don't understand how I could achieve the same result without instantiating the objects before hand and validating them?
The class isn't high level, we have only just learned polymorphism.
Usually, the data which tells you which objects to create comes from an external source: a file, a socket, another object etc. In your case, you could use a text file. Create the Grade instances passing the values you read to the constructor and then call validate and cost on each.
public class PipeFactory(){
public Pipe CreatePipe( int minGrade, int maxGrade, boolean hasColour0, boolean hasColour1, boolean hasColour2, boolean hasIns, boolean hasReinf ){
if( (minGrade == 1 || maxGrade == 3) /* ... Complete this condition yourself */ )
return new TypeIPipe();
if( (minGrade == 2 || maxGrade == 4 /* ... Complete this condition yourself */ )
return new TypeIIPipe();
//If for other types...
//If no pipe was created, parameters are invalid, so we throw an exception
throw new InvalidArgumentException( "Can't create a pipe with these parameters" );
}
}

How to write a private method that returns True for certain peramaters?

So the exact wording is,
"Write a private method isValid(aRating) that returns true if the given rating is valid, which is between 1-10."
private void isValid(aRating)
{
}
What Goes in the Method above in order to return a true value if given rating is valid, Validity meaning a number 1-10.
This is what i attempted, the instructor wants it the "proper way" This is just an example of what i attempted at, It is a different program completely.(Ignore if confusing).
private void isValid(int hour, int minute)
{
if (hour >= 0 && hour <=23)
{
System.out.println("Hour is valid");
hourIsValid = true;
}
else
{
System.out.println("Hour is not valid");
hourIsValid = false;
System.exit(0);
}
}
Would this be correct
private boolean isValid(int aRating)
{
if (aRating >= 1 && aRating <= 10)
return true;
else
return false;
}
The problem demands a function that returns true under some conditions, so the signature cannot be
private void isValid(int aRating) {}
it needs a return type. Now, true's type is boolean, so make it
private boolean isValid(int aRating) {
return /* validity test here */;
}
Calling Private Methods
Calling a private method from a public one is exactly the same as calling any other method:
public void doStuff() {
System.out.println("Stuff done.");
}
private void doOtherStuff() {
System.out.println("Other stuff done.");
}
public void showHowItWorks() {
doStuff();
doOtherStuff();
// or if you prefer this style:
this.doStuff();
this.doOtherStuff();
}
The important difference is that you can only call private methods from inside the class where they were defined:
class PublicExample {
public static void doStuff() {
System.out.println("Stuff done.");
}
}
class PrivateExample {
private static void doStuff() {
System.out.println("Stuff done.");
}
}
class Example {
public static void Main(String[] args) {
PublicExample.doStuff(); // Works
PrivateExample.doStuff(); // Doesn't work (because it's private and defined in a different class)
}
}
Return Values
private void isValid(int hour, int minute) {
if (hour >= 0 && hour <=23) {
System.out.println("Hour is valid");
hourIsValid = true;
} else {
System.out.println("Hour is not valid");
hourIsValid = false;
System.exit(0);
}
}
The problem with this approach is that your program immediately dies if you input a bad hour or minute. What if I want to loop until I get a good input?
I think the main problem is that you don't know how to return a value from a method. Here's an example of a function that always returns true:
public static boolean trueExample() {
return true;
}
public static void main(String[] args) {
boolean returnValue = trueExample();
System.out.println("trueExample() returned " + returnValue);
}
You can also make it more complicated:
/**
* #return the input value minus one.
*/
public static int oneLess(int num) {
return num - 1;
}
public static void main(String[] args) {
int num = 10;
// Print 10
System.out.println(num);
// Print 9
num = oneLess(num);
System.out.println(num);
// Print 8
num = oneLess(num);
System.out.println(num);
}
Here's one that will return true if num is in the range 10-20 and false otherwise:
public boolean isValid(int num) {
return num >= 10 && num <= 20;
}
This version does exactly the same thing, but you may find it easier to read since it's more explicit:
public boolean isValid(int num) {
/* Numbers less than 10 are invalid */
if(num < 10) {
return false;
}
/* Numbers greater than 20 are invalid */
else if (num > 20) {
return false;
}
/* By process of elimination, everything else is valid */
else {
return true;
}
}
Let me know if that's not enough to help you with your problem.
Just like you would call any normal method as long as the private method is visible to the public method.

Categories