In need of help of with a while loop program [closed] - java

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.

Related

Understanding a coding challenging in finding the first duplicate value in an array [closed]

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 :)

For-loop condition conventions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I had recently a discussion about the use of non-counter related conditions in for-loops in Java:
for(int i = 0; o.getC() < 10; i++)
o.addC(i);
Does anyone know if there are any "official" conventions for for-conditions like this? In my opinion it's easier to read compared to an equivalent while-loop because all loop-parameters are together in the first line:
int i = 0;
while(o.getC() < 10) {
i++;
o.addC(i);
}
Or even worse:
int i = 0;
while(o.getC() < 10)
o.addC(++i);
for loops are used in pretty much every situation over equivalent while solution. Arrays, lists, standard data structures.
On the other hand while is commonly used with streams and for infinitely long iterations..
Most developers will expect a for statement to consist of three things:
Initialization of a variable
Termination condition based on the variable
Increment on the variable
If you change your code to contain unexpected things it will get harder to read and thus harder to maintain.
Furthermore, I think the while loop makes your intention clearer: do something while o.getC() is less then 10. This "something" happens to be: add an incrementing number.
Long story short: use a while loop for "non-counter related conditions".
A nice thing about for loops is there is a shortcut method. So if you want to do all of the items in an array you can just do the following:
(double number : arrayName)
where double is the type, number is the name you are giving each element (it doesn't matter really what you call it, you will refer to each value there as "number" in this case). And arrayName is the name of the array you are referring to.
If you want to reach each element/object this is the fastest way.
How about:
for(int i = 0; i < MAX_ITERATIONS; i++)
{
o.addC(i);
if (o.getC() >= 10)
return o; // or break
}
This prevents an infinite loop if addC is not really doing what you expect.

Finding odd number results using the for loop [closed]

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 8 years ago.
Improve this question
I am experiencing some problems with finding odd results w/ the user input. I am not sure how to code the for loop statement to get the odd results only. Current for loop statement is fixed to increment by two, but this will only work if the user enters odd numbers as well ex(0,5). Sorry i really dont have much experience with forloops, i tried nesting the for loops, but it only made it more confusing. This is my for-loop statement;
for(counter = num1; counter <= num2; counter+=2){ //this is my for loop statement
System.out.println(counter);//print out all of the odd values
}
}
If a user enters an even number, just fix it before the loop:
//if num1 is even, move it up to the next odd number
if (num1 % 2 == 0) {
num1++;
}
//print all of the odd values
for (int counter = num1; counter <= num2; counter+=2) {
System.out.println(counter);
}
As an alternative to the accepted answer:
//if num1 is even, move it up to the next odd number
num1 |= 1;
It probably doesn't really matter, but I think it's neater that way.

Generate a random integer within a given range AND is even ONLY [closed]

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.)

Subroutine dice rolling assignment [closed]

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()
}
}

Categories

Resources