This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I have recently begun programming at university and I am a little stumped with one of my tutorial problems.
I basically need to create a method within a class which uses the Random.nextInt()
method to flip a coin, assigning and saving the value once the process has been run.
MY current attempts include this:
public void Flip() {
int flipResult;
flipResult = mRandNumGen.nextInt(1);
if(flipResult == 0)
{
mFace = 'H';
}
else
{
mFace = 'T'
}
}
mFace and mRandNumGen are variables which have been declared already outside the specific method. What exactly is going wrong here? I can't for the life of me get this to work :/
Simple way to do this:
if (mRandNumGen.nextBoolean()) {
mFace = 'H';
} else {
mFace = 'T';
}
The first argument in Random.nextInt is an exclusive upper bound, not inclusive.
So with n=1 it will always return 0. for n=2 it will return either 0 or 1 which is what you're looking for.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last month.
I need to create a method for my OOP lab, the details are as the following:
A ThreeWayLamp class models the behavior of a lamp that uses a
three-way bulb. These bulbs have four possible states: off, low light, medium
light, and high light. Each time the switch is activated, the bulb goes to the next
state (from high, the next state is off, from off to low etc). The ThreeWayLamp
class has a single method called switch() which takes a single int parameter
indicating how many times the switch is activated. (you need to throw an
exception if its negative). The Switch() method should simply print out to
System.out a message indicating the state of the bulb after it has changed.
public class ThreeWayLamp {
public String[] States = {"Off","LowLifght", "MediumLifght", "HighLight"}; // an array of the 4 states
public void Switch(int switchState){
//used an if condition to determine what to print based on the parameter switchState
if ((switchState <= States.length) && (switchState >= 0)){
System.out.println(States[switchState]);
}else if (switchState < 0 ){
System.out.println("Wrong input, try again with diffrent number");
}else if (switchState >= States.length){
} //This condition is the issue, how to form a condition that will solve this problem
}
If the parameter is larger than the array's length, an error will occur, so the issue is how to form a condition that will make the array loop again around itself when it reaches its last index.
For example, if the input was 5, then the method should print LowLight.
Is there a possible condition or function that could solve this issue, or should I change the entire structure of the code?
You can solve this problem by using a modulo operator:
System.out.println(States[switchState % States.length]);
Instead of using the less than condition, you can try using mod to repeat the indexes of your String array.
Try below code:
public class ThreeWayLamp {
public String[] States = {"Off","LowLifght", "MediumLifght", "HighLight"}; // an array of the 4 states
public void Switch(int switchState){
if ((switchState > 0){
System.out.println(States[switchState % States.length]); // states.length = 4 in your case
} else {
System.out.println("Wrong input, try again with diffrent number");
}
}
Using modulo you can ensure the index will always be within the size of the array
4 % 4 = 0
5 % 4 = 1
6 % 4 = 2
7 % 4 = 3
8 % 4 = 0
9 % 4 = 1
...
public void Switch(int switchState){
if ((switchState < States.length) && (switchState >= 0)){
System.out.println(States[switchState]);
} else if (switchState < 0 ){
System.out.println("Wrong input, try again with diffrent number");
} else {
Switch(switchState % 4);
// or
// System.out.println(States[switchState % 4]);
}
}
Also, variable and method names should start with a lower case
This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 1 year ago.
I am a Java newbie and I am facing this error here. Any help would be appreciated. Thank you!
The error is:
symbol: method isInteger(double)
location: class number
Program:
int num = Integer.parseInt(num1.getText());
double square = Math.sqrt(num);
if (Number.isInteger(square))
outputlbl.setText("Number is a perfect square");
else
outputlbl.setText("Number is not a perfect square");
I think you are confusing the Java method with Javascript Number.isInteger().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
Unfortunately, we don't have this in java directly.
However, you can use the below code to check if double is an integer or not.
double d = 5;
if( (d % 1) == 0 ) {
System.out.println("Yes");
}
else{
System.out.println("No");
}
PS: This is one of the ways to check if double is an integer or not . If you dig more in java, you will certainly find more ways to do the same.
The Java class Number doesnt have this function. (it exists in javascript though)
Alternatively you can write an easy helper function to solve this problem:
private boolean isInteger(double num)
{
if (num==(long)num)
return true;
return false;
}
The code should be pretty self explanatory.
This question already has answers here:
Java - How do you make a jButton# index take the value of an int variable?
(2 answers)
Closed 7 years ago.
I am making a game in Java. I want to be able to check whether a level has been previously visited.
I came up with this:
public class LevelTracker {
boolean depth1visited = false;
boolean depth2visited = false;
// ..
boolean depth100visited = false;
private boolean LevelTracking() {
if (Dungeon.depth == 1) {
depth1visited = true;
}
if (Dungeon.depth == 2) {
depth2visited = true;
}
// ..
if (Dungeon.depth == 100) {
depth100visited = true;
}
}
}
In my situation, each depth must be checked independently since any level might be accessed from any other level. So this:
if (depth > deepestdepth) {
deepestdepth = depth;
}
won't work in my situation. Unless I'm wrong, which is possible. I am, as you can probably tell, a novice at this.
What is a better way to do this? Could a for loop be used in this situation?
Use arrays, which can be addressed by index. This can replace all your ifs and your 100 separate variables.
boolean[] depthVisited = new boolean[100]; // default values: false
Then you can access the array by calculating an index.
depthVisited[Dungeon.depth - 1] = true; // 0-based index
No for loop is necessary.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am preparing for an exam next week, and I decided to look for some exam questions online for better preparation.
I came across this question and the answer is c. But I really want to know how or the step by step process to answer to answer a question like this. The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method? Whenever I get to a question like this is their anything important I should breakdown first?
private int[] myStuff;
/** Precondition : myStuff contains int values in no particular order.
/*/
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--)
{
if (myStuff[k] < num)
{
return k;
}
}
return -1;
}
Which of the following best describes the contents of myStuff after the
following statement has been executed?
int m = mystery(n);
(a) All values in positions 0 through m are less than n.
(b) All values in positions m+1 through myStuff.length-1 are
less than n.
(c) All values in positions m+1 through myStuff.length-1 are
greater than or equal to n.
(d) The smallest value is at position m.
(e) The largest value that is smaller than n is at position m.
See this page to understand a method syntax
http://www.tutorialspoint.com/java/java_methods.htm
int m = mystery(n); means this method going to return int value and you are assigning that value to a int variable m. So your final result is m. the loop will run from the array's end position to 0. loop will break down when array's current position value is less than your parameter n. on that point it will return the loop's current position. s o now m=current loop position. If all the values of the loop is greater than n it will return -1 because if condition always fails.
Place the sample code into a Java IDE such as Eclipse, Netbeans or IntelliJ and then step through the code in the debugger in one of those environments.
Given that you are starting out I will give you the remainder of the code that you need to make this compile and run
public class MysteriousAlright {
private int[] myStuff;
public int mystery(int num)
{
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
public static void main(String[] args) {
MysteriousAlright ma = new MysteriousAlright();
ma.setMyStuff(new int[] {4,5,6,7});
int m = ma.mystery(5);
System.out.println("I called ma.mystery(5) and now m is set to " + m);
m = ma.mystery(3);
System.out.println("I called ma.mystery(3) and now m is set to " + m);
m = ma.mystery(12);
System.out.println("I called ma.mystery(12) and now m is set to " + m);
}
public void setMyStuff(int[] myStuff) {
this.myStuff = myStuff;
}
}
You then need to learn how to use the debugger and/or write simple Unit Tests.
Stepping through the code a line at a time and watching the values of the variables change will help you in this learning context.
Here are two strategies that you can use to breakdown nonsense code like that which you have sadly encountered in this "educational" context.
Black Box examination Strategy
Temporarily ignore the logic in the mystery function, we treat the function as a black box that we cannot see into.
Look at what data gets passed in, what data is returned.
So for the member function called mystery we have
What goes in? : int num
What gets returned : an int, so a whole number.
There are two places where data is returned.
Sometimes it returns k
Sometimes it returns -1
Now we move on.
White Box examination Strategy
As the code is poorly written, a black box examination is insufficient to interpret its purpose.
A white box reading takes examines the member function's internal logic (In this case, pretty much the for loop)
The for loop visits every element in the array called myStuff, starting at the end of the array
k is the number that tracks the position of the visited element of the array. (Note we count down from the end of the array to 0)
If the number stored at the visited element is less than num (which is passed in) then return the position of that element..
If none of elements of the array are less than num then return -1
So mystery reports on the first position of the element in the array (starting from the end of the array) where num is bigger than that element.
do you understand what a method is ?
this is pretty basic, the method mystery receives an int as a parameter and returns an int when you call it.
meaning, the variable m will be assigned the value that returns from the method mystery after you call it with n which is an int of some value.
"The part where I got stuck is trying to logically understand how a int m = mystery(n); How can a number equal a method?"
A method may or may not return a value. One that doesn't return a value has a return type of void. A method can return a primitive value (like in your case int) or an object of any class. The name of the return type can be any of the eight primitive types defined in Java, the name of any class, or an interface.
If a method doesn't return a value, you can't assign the result of that method to a variable.
If a method returns a value, the calling method may or may not bother to store the returned value from a method in a variable.
Sooo I started taking my second computer science class ever! For my first class we used python and for this class we're using Java. Our first assignment (pretty much just practice) is to convert this craps program from Python to Java and I'm just having a hell of a time.
Could someone please help with what I've done and umm give me some advice? Maybe a good site for a beginner.... Someone that kinda knows Python (only from a first CS course perspective).
1) In python
def winCraps():
roll = rollDice()
if roll == 7 or roll == 11:
return True
elif roll == 2 or roll == 3 or roll == 12:
return False
else:
return rollForPoint(roll)
This is my attempt at the conversion of it over to java
public int winCraps{
roll = rollDice();
if (roll = 7 && 11){
return (true);
}
else (roll =2 && 3 && 12){
return(false);
}
else{
return rollforPoint(roll);
}
}
2) Python
def rollDice():
raw_input("Press <Enter> to roll...")
die1 = randrange(1,7)
die2 = randrange(1,7)
sum = die1 + die2
print "You rolled", die1, "+", die2, "=", sum
return sum
This one confused the hell out of me. What would randrange be in Java??
Java
static int rollDice(){
System.out.print("Press <Enter> to roll...");
double die1 = Math.random();
double die2 = Math.random();
die1 = (int) die1*6+1;
die2 = (int) die2*6+1;
int sum = (int)die1 + (int)die2;
System.out.println("You rolled "+die1+ " + "+die2+ " = "+sum+".");
return sum;
}
*please bear in mind that I'm just learning this stuff lol
You need to fix your if statements the "==" operator checks for equality, and you must put the variable you are checking against in each section of the statement.
public int winCraps{
roll = rollDice();
if (roll == 7 || roll == 11) {
return true;
}
else if(roll == 2 || roll == 3 || roll == 12) {
return false;
}
else{
return rollforPoint(roll);
}
}
In you rollDice() method, the way you assign values to each die is incorrect. I recommend reading up on random numbers (since this is homework, I'll leave that to you).
Also, remember in java you must always end each statement with a semicolon
What would randrange be in Java?
You can get a random integer in a specific range from Java's Random class by calling the nextInt(int n) method. For example,
Random rand = new Random();
int a = rand.nextInt(7);
will give you a random integer >= 0 and < 7. This isn't exactly the same as randrange in Python, but you could use it as the index to an array of objects, or as the value of a roll of a single die.
Randrange can be replaced by methods in java.util.Random. Like Python, Java has an extensive standard library which you should reference.
1) In Java "OR" operator is "||" not "&&" and comparison operator is "==" as in Python
So
if roll == 7 or roll == 11:
Should be
if( roll == 7 || roll == 11 ) {
and not
if( roll = 7 && 11 ){
2) randrange is : random generator from there you can search: Random in Java
Which will lead you to something like: Random.nextInt()
Use this algorithm ( a) search Internet for Python function, b) understand what it does c) search it in java ) for the next assignment you have and you're done.
You can always ask here again, that's what this site is all about after all
I'd recommend that you look up the docs on randrange(). Once you know exactly what it does, google for the those keywords, plus the word Java.
One thing you'll quickly discover in working with languages is that the APIs can be very different. There might not be an equivalent of randrange in Java, but you might be able to find two or three functions that you can combine to do the same thing.
System.out.print isn't going to cause the system to wait for someone to hit the enter key. For that, you need to do something with System.in, most likely System.in.read(), as it blocks while waiting for input.
Also, in Java, a program starts executing with the main method. To be exact, an executable class starts something like this:
// You'll need the Random class, as per other answers
import java.util.Random;
// assuming WinCraps is the class name
public class WinCraps {
// args in this example is a string array of command-line arguments
public static void main(String[] args) {
// This is where your main method (that calls winCraps?) would be
}
// Other methods
}
Also, any method in this class called directly from main must also be static.
Write out in English what the Python program does. Go through it line by line and explain to yourself what computations are evoked, in other words...what is happening?
Afterwards, write the Java program from that description.
Never ever try to convert the text of a program from one language to another. You'll run into a LOT of problems that way because every language is different, no matter how similar they look.
One major error in your first program that you have in the Java conversion is the conditionals.
Something like (roll =2 && 3 && 12) assigns 2 to roll and then applies AND operators. You also forgot the if. You have elseif in Python.
You want something like:
else if(roll==2 || roll==3 || roll==12)
As for random numbers, there is a function for that in Java.