Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm just learning subroutines and I'm still very, very amateurish at this. My assignment asks me to toss two dice, display what the dice display (random numbers), display total of the two die, and let the program continue until 7 or 11 is the total. We haven't done anything on arrays, so I don't know if I should use them or not.
Also, I was going to use a for loop, but how would I get the program to stop at either 7 or 11 using it? Should I try another loop?
Please help guide me on what I have to do! I'm very confused about how to make the methods and put them into the main method. Just an explanation would do!
Thank you!
Here's the pseudocode for this problem. I won't give you the actual code but this will set you in the right direction:
Loop forever: {
Integer A = Random #1-6
Integer B = Random #1-6
Integer total = A + B
If total == 7 or total == 11 BREAK from the loop
Print total
}
Some more hints: Looping forever is usually achieved by setting up a while loop whose condition is always true. For example, while (true) or while (1 == 1).
Also, look into the java.util.Random class for generating a random number. It's really straightforward and it's good to start learning how to use the Java docs early in your learning process.
I would suggest a while loop. In your case,
instantiate the two dice
while the total isn't either 7 or 11 {
roll again
}
print out the result of the roll that wasn't either 7 or 11.
should be a reasonable starting point for you. I won't go into too much detail so that you still get the chance to implement the idea yourself and learn from it. If you don't know how to simulate a dice roll, #Kon's answer is helpful.
You may write a subroutine that returns the total number and call it in main method in while-loop
class Rolling-dice {
public static int roll() {
// roll the first dice and display the number
// roll the second dice and display the number
// return total`number
}
public static void main(String[] args) {
int result = roll();
// while result not 7 or 11 call roll()
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I am in my first semester of a Java Course. I am struggling to understand how I put exclusiveness on a statement. I am writing a Class for an Object Couch. I have tried to build a well formed class, but for the outcome from my main, in the console it must only have 4 or 8 legs on the couch. There is no user input as I am hard coding the variables, but I want to be sure that if I hard code for 5 legs it will stop me or an error message will pop up. Any suggestions?
public void setNbrLegs(int nbrLegs){
if ((nbrLegs == 2) || (nbrLegs == 4)){
this.nbrLegs = nbrLegs;
}
}
I tried putting an "else" with a message that that number is bad, but what is did was bypass my error message and just insert the incorrect number ofLegs as 5.
Consider looking for the opposite: a condition where you must fail. From there, you can use runtime exceptions to ensure a few things:
The invalid state is not applied
A developer passing this invalid state will get an exception, and have a clear reason to fix their code
You no longer have to worry about invalid state further on in the method (i.e. legs will only be 2 or 4 further on).
In doing so, your method may end up looking like this:
public void setNbrLegs(int legs) {
if (legs != 4 && legs != 2) {
throw new IllegalArgumentException("Can only have 2 or 4 legs");
}
this.nbrLegs = legs;
}
This preconditional checking is also good to do early in your methods (fast-fail), as it will prevent excess work being done for a method that will only "fail".
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am currently practicing with my coding skills and one of the challenges I ran into was finding the first duplicate value produced in an array. I had solve the challenge, but not in a timely manner. I looked at the solution for the problem and ran into this solution and wanted help in understanding how it exactly works. I have the solution commented in the areas that I understand and what exactly is the purpose of that block of code, but I would like help in understanding the if-statement why it works the way it does.
int firstDuplicate(int[] a) {
for(int i=0;i<a.length;i++)
//Checks ???????????
if(a[Math.abs(a[i])-1]<0)
return Math.abs(a[i]);
//Make the checked value negative
else{
a[Math.abs(a[i])-1]=-a[Math.abs(a[i])-1];
}
//If there are no duplicates it returns -1
return -1;
}
Constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.
Welcome to SO. I will not give you the exact answer but instead provide you with tools for you to figure it out.
In order for you to figure out this code, you need to debug it. Here are some ways you could go about it.
Set a breakpoint just prior to calling the function (look up how to do this for your IDE), thereafter step into your code line-by-line.
You could use a combination of temporary variables and System.out.println() statements. Looking into your code, break it down into modular bits that you can track. For instance you could re-write the expression inside the if statement as
int currentElementAbsolute = Math.abs(a[i]);
System.out.println(currentElementAbsolute);
int difference = currentElementAbsolute - 1;
System.out.println(difference);
int element = a[difference]
System.out.println(element);
if (element < 0)
{
return Math.abs(a[i]);
}
As you can see, for each operation/line, I print out the current value thus keeping track of events. Practice this and re-write the else part
PS: Upon completion you will realise this method fails to capture all duplicates when certain type of numbers are used. Happy Hunting :)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm a novice programmer is looking to get help with a program I've been working on for hours now.
Anyway my issue happens to be with initializing my "sum" variable in a way so that it is not equal a number or become an input. (It's set to equal 0 in my program)
I also seem to be struggling with my while loop statement as I can't think of a condition in which I don't cause the program to terminate or cause a infinite loop.
Any help at this point would highly appreciated.
I'm assuming you are trying to compute sum of integers from 1 to n, where n is input from the user.
One of the simpler ways to do that is to use a for loop as below
for(int i = 1; i <= n; i++) {
sum = sum + i;
}
or using while loop
while(input > 0) {
sum = sum + input;
input = input - 1;
}
Alternatively, sum of first N natural numbers is given by formula n*(n+1)/2, so you might as well do
int sum = (n * (n+1))/2;
Ensure that n is a positive number > 0 through an if conditional
your While loop is going infinity as your input is never 0 until you give it.
So you have to deal with your input.
Possibly use or declare input=0 so that when your while loop goes for the execution for 2nd Time...It finds 0.
Hope this helps...Please share doubts if any.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to know how to translate this:
into a Java process that looks like:
public static float computeAverage(float [] i){
//I have no idea what this is supposed to be.
}
or perhaps even
public static double computeAverage(double [] i){
//Still have no idea what this is meant to be.
}
If it's easier to answer with doubles, that's fine, but I really don't need that level of precision.
*Edit:*Okay, tell me if this looks right:
public static float computeAverage(float [] i){
float tally = 0f;
for(int x=0;x<i.length;x++){
tally = tally + pValue(i[x]);
}
return tally / i.length;
}
public static float pValue(float i){
return 2 - 1f/i;
}
I don't want to do your work right away, because it won't help you in the future. But I'll try to give you hints.
Java elements
The different elements that you might need are the following:
the number n, which is the number of elements in your input array, can be accessed using myInput.length
to iterate with a moving k index, you'll need a for loop. Check this out to know how to use for loops.
you'll have to be careful that in Java, arrays are indexed starting at 0, not 1. So to access Ck, you'll actually write myInput[k-1].
Break down your problem
What do you want to achieve? You're not just "translating this formula into Java code", but you're writing a method (a function) which, given an input array of Ci, returns an average following the specified formula.
I think your assignment is to write the following function:
Maybe you should try to:
write a little method for p()
write a for loop that performs a sum (the internet is full of these)
adapt your for loop using p()
divide the result of the for loop by n
return the divided result
UPDATE: it's much easier to help you once you've tried something :)
Your code looks fine overall now. According to your formula I think you're adding the wrong value to the sum in your loop).
It should probably be: tally = tally + pValue(i[x])
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am having trouble generating this code which I'm sure I'm just in a coder's block or something because it seems as though it should be easy but can't get it for the life of me.
I have a program which needs random numbers generated within a certain range which is to represent money. The stipulation is that the money need be in between 2 and 200 and represent only even dollars only so $2, $4, $6...so on. I have done extensive searching online which yield a bounty of code to represent random numbers in a range in java but not the part about being only even.
Any ideas?
If you wanted to be clever, you could make sure the least significant bit of the number is not set:
int num = (new Random().nextInt(199) & ~1) + 2;
This will ensure that the number is always even.
Thanks Eyal Shneider and Omaha
Marcelo's comment from the OP is the correct answer, though.
Get a number between 1-100, and multiple by 2:
int num = (new Random().nextInt(100) + 1) * 2;
int rand = new Random.nextInt(200);
int result = 2;
while(result < rand) {
result += 2;
}
return result;
(I'd make it recursive but I've got to go meet my wife for dinner.)