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;
}
}
Related
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++;
}
I'm learning object-oriented programming and started learning about inheritance. The assignment my teacher gave me was to make a counter object with 6 "buttons": Increment, Decrement, Reset, AddMemory, ResetMemory, and Quit. It is fairly straight-forward what each button does.
The requirements are that I have to use the JOptionPane command, I have to make a Counter class with a counter attribute, increment, decrement, reset, and quit methods, I have to make a MemoryCounter class with a memory attribute, restMemory, and addMemory method. I also have to make a MemoryCounterConsoleMenu class which makes the input box from the JOptionPane command and executes the appropriate method. The final thing I have to do is make a MemoryCounterTest class that brings the MemoryCounterConsoleMenu and MemoryCounter classes together
So I did all that and here it is:
The first one is the Counter class
public class Counter
{
private int counter = 0;
public void increment()
{
setCounter(getCounter() + 1);
}
public void decrement()
{
setCounter(getCounter() - 1);
}
public void reset()
{
setCounter(0);
}
public void setCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return counter;
}
}
This is the MemoryCounter class
public class MemoryCounter extends Counter
{
private int memory = 0;
public void resetMem()
{
setMemory(0);
}
public void addMem()
{
setMemory(getCounter());
}
public void setMemory(int memory)
{
this.memory = memory;
}
public int getMemory()
{
return memory;
}
}
Next is the MemoryConsoleMenu
public class MemoryCounterConsoleMenu
{
static MemoryCounter memCounter = new MemoryCounter();
static Counter counter = new Counter();
public static int console()
{
System.out.println(memCounter.getMemory());
Object[] options = {"Reset Mem", "Add Mem", "Increment", "Decrement", "Reset", "Quit" };
int objectIndex = JOptionPane.showOptionDialog(null, "Counter = " + counter.getCounter() + "Memory = "
+ memCounter.getMemory(), "MemoryCounter",JOptionPane.PLAIN_MESSAGE,
JOptionPane.PLAIN_MESSAGE, null, options, options[5]);
return objectIndex;
}
public static int change(int objectIndex)
{
if(objectIndex == 0)
{
memCounter.resetMem();
return 1;
}
else if(objectIndex == 1)
{
memCounter.addMem();
return 2;
}
else if(objectIndex == 2)
{
counter.increment();
return 3;
}
else if(objectIndex == 3)
{
counter.decrement();
return 4;
}
else if(objectIndex == 4)
{
counter.reset();
return 5;
}
else
{
return 6;
}
}
}
Finally, there is the MemoryCounterTest
public class MemoryCounterTest
{
public static void main(String[] args)
{
MemoryCounterConsoleMenu memoryConsole = new MemoryCounterConsoleMenu();
for(int i = 0; i != 6;)
{
i = memoryConsole.change(memoryConsole.console());
}
}
}
Everything works properly except for the memory value. It stays at a constant zero. I've done some troubleshooting myself and found that the only problem in the code is in the "addMem()" method is the MemoryCounter class particularly the implementation of the "getCounter()" method. It will only return 0 for some reason.
After figuring this out I have made no ground on why the problem is occuring or how to fix it
It stays at 0 because they are two separate counters.
MemoryCounter class extends the Counter class, so you don't need a separate
static Counter counter = new Counter();
Just do everything via memCounter.
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";
}
}
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;
}
}
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.