Subtracting a variable in a loop in Java - java

I'm trying to calculate how many rounds can a player play lotto and joker games with a fixed amount of money.
public static void example () {
int money = 200;
int lottoCost = 4;
int jokerCost = 3;
int costTogether = lottoCost+jokerCost;
int rounds = 0;
for (int i = money; i <= 0; rounds++) {
money = money-costTogether;
}
System.out.println("With " + money + " euros, you can play "
+ rounds + " rounds.");
System.out.println("");
}
That code currently prints the text "With 200 euros, you can play 0 rounds."
So it doesn't add a +1 to the rounds variable. What am I doing wrong?

In general, it is good to use the same variable in the 3 parts of the for. Note that the loop initialization part (the first one int i = money) is only run once, and you don't modify i during the loop. Furthermore, the condition is false from the beginning (200 < 0) so the loop is not even run once
I think what you are looking for is a simple int division, just replace your for block with this :
rounds = money / costTogether;

Your stopping condition is wrong, so the loop is never exectued. You should use >= instead. Also, you never change nor use i.
Here is a corrected version, using currMoney instead of i to be more meaningful.
int rounds = 0;
for (int currMoney = money; currMoney >= costTogether; currMoney -= costTogether) {
rounds++;
}
But obviously here, you only need a simple division as #Fredszaq pointed out in his answer:
int rounds = money / costTogether;

This condition i <= 0 is never true and probably dont get incremented
i guess its a typo ,
Greater and Lessthan you need to be aware as they change context .

Your for-loop is not defined correctly. i starts at money = 200. You want to repeat the loop as long as i <= 0. So you require i starting at 200 while not being larger than 0. That's why your loop isn't executed at all.
Instead prefer a while loop for your case. It is more readable:
while (money >= costTogether) {
money = money - costTogether;
rounds++;
}
If you want to use a for loop, you can declare it like that:
for (int i = money; i >= costTogether; i -= costTogether) {
rounds++;
}

You're only incrementing rounds, in a roundabout way, when the loop runs.
The loop runs while i <= 0 - i starts equal to money, which equals 200, so the loop never runs and the rounds value is not incremented.
You're also not changing i in the loop - I suspect you'd rather want while i >= 0 and decrement i in the loop?
for (int i = money; i >= 0; rounds++) {
money = money-costTogether;
i--;
}

Related

Method to print odd numbers between 1 and 100

I have to write a method that returns/prints the odd numbers between 1 and 100, but I have to use another method, which checks whether a given integer is odd or not:
static boolean isOdd(int c) {
boolean d;
d = c % 2 != 0;
return d;
}
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?), but I think what I'm really struggling with is "connecting" both methods. So the numbers actually run through isOdd() which determines whether they are odd.
I've tried these two options so far, but they're not working.
Option 1:
static void func1() {
int number = 1;
while (number < 100 && isOdd(number)) {
System.out.println(number);
number = number + 1;
}
}
Option 2:
static void func1() {
int i;
for (i = 1; i < 100; i++) {
isOdd(i);
}
System.out.println(i);
}
Your attempt #1 is closer to your goal ;)
you are right that you can use while and for (and probably other kinds of processing multiple numbers, but that just for the sake of completeness, forget it for now)
your println (or print) should be within the loop because you want to print more than just one number.
in you current attempt #1 you end your loop with the first odd number: 1 This doesn't count up very far ;)
So you have to use an if inside your loop where you check the result of isOdd(number) and only print if it's odd.
But the loop has only the upper bound limit as condition (number < 100) as you want to check all the numbers.
Smartass hint (try it only after your program works fine): if you count up by 2 instead by 1 (number = number + 2;), your program will only need half the time - and you could even skip the isOdd check ;-)
I'm guessing that I have to use either a for- or while-loop (probably can be done with both?)
Yes. for-loops are just syntactic sugar for special while-loops:
for (init_stmt; cond; incr_stmt) body_stmt;
is equivalent to
init_stmt;
while (cond) {
body_stmt;
incr_stmt;
}
Let's first write this using a for-loop.
for-loop
for (int i = 1; i < 100; i++)
if (isOdd(i))
System.out.println(i)
Note that we can (and should!) do the declaration of i as int in the for-loop initializer.
Now, we may translate this to an equivalent while-loop:
while-loop
int i = 1;
while (i < 100) {
if (isOdd(i))
System.out.println(i);
i++;
}
Mistakes in your attempts
Attempt 1
You've mistakenly included the check in the condition (rather than using it in an if inside the loop body); the first even number (2) will cause the loop to terminate.
Attempt 2
You're not even using the return value of isOdd here. You're unconditionally printing i after the loop has terminated, which will always be 100.
The ideal implementation
Ideally, you'd not be filtering the numbers; you'd directly be incrementing by 2 to get to the next number. The following loop does the job:
for (int i = 1; i < 100; i += 2)
System.out.println(i);

Java - my while loop works, but my for loop doesn't - having trouble converting it

I assume that if I can't convert my while loop into a for loop, then I don't fully understand the concepts here. Here's my working while loop:
(I am trying to implement a program, which calculates the sum 1+2+3+...+n where n is given as user input.)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = Integer.valueOf(scanner.nextLine());
int sum = 0;
int i = 0;
while (i < number) {
i++;
sum += i;
}
System.out.println(sum);
I was looking at this user's answer here: https://stackoverflow.com/a/36023451/11522261
and tried to implement it, but it's not working.
.....
for (i = 0; i < number; i++){
sum += i;
}
System.out.println(sum);
It looks like the conditions of For Init expression statement and ForUpdate are set right, but I'm having trouble understanding the differences here.
Also, it looks like this exercise is trying to teach loops to solve iterative problems. But I suspect that this isn't helping me practice recursion. Perhaps there is a recursive solution to this problem which would be better. Just thinking out loud here. Thanks!
The difference is that in your while loop, you're incrementing i before adding it to sum, but in your for loop, it's after.
If the while is producing the right result, you can adjust your for by starting at 1 instead of 0 and continuing while <= number instead of < number.
For completeness, here's how your current for loop works:
i = 0
If i < number is not true, exit the loop; otherwise, continue to Step 3
sum += i (i is still 0)
i++
Goto Step 2
On the second pass, i < number is 1 < number so still true if number is greater than 1, so you go to Step 3, do sum += i while i is 1, then continue.
Eventually i < number isn't true anymore, and the loop exits.
For problems like this, the best approach is usually to use the debugger built into your IDE to step through the code statement by statement, looking at the values of variables as you go. That can reveal how things work really well. This article may be helpful: How to debug small programs
Since you are incrementing the value of i before adding it to sum in the while loop, the same thing needs to be done in case of for loop as well. Given below is the implementation using the for loop:
for (i = 0; i++ < number; ){
sum += i;
}
System.out.println(sum);
Use <= instead of <. This will solve Your problem, and make sure you understand why will the following code would work. I would recommand you to use a paper and pencil and start writing down the values of i and sum after every iteration.
for (i = 1; i <= number; i++) {
sum += i;
}

Subtraction using while loop Java

So i'm trying to write a programme whereby the user enters two integers .
The programm is supposed to subtract 5 from the second integer entered in a loop depending on the first number entered. (so the first number should dictate how many times it will loop.
public int getScheme1() {
while (Mark >= 20) {
System.out.printf((Mark = Mark - 5) + Mark + " ");
}
for (int Day = 1; Day <= 20; Day++) {
System.out.printf("( " + Day + "):" + Mark + " ");
}
return Mark;
}
All my code does is print the user's second input integer 20 times.
Also im sorry im totally new to java
you must call this function in your main program.
public int getScheme1 (int num1, int num2){
for(int i = 1 ; i >= num1 ; i++ ){
num2 -= 5;
}
return num2;
}
to call it simply use getScheme1(num1,num2);
Based on what you described, you are looking for something like this:
Scanner input = new Scanner(System.in); //create a scanner to get user input
int a1 = input.nextInt(); //get 2 ints from the user
int a2 = input.nextInt();
for(int i = 0; i < a1; i++) { //loop as many times as a1 specifies
a2-=5; //subtract 5 from a2 each time it loops
}
System.out.println(a2);
The key part of this is the for loop, which works in the following:
for(variable; condition; increment),
basically, what the for loop I wrote is saying:
Set i = 0 at the start. If i is meeting the condition (in this case being less then a1), then loop. The increment part is called when it finishes running the code block, it now makes i bigger (in this case 1 bigger using ++) Another important thing to note is that the first time the loop runs, i = 0.
So for example, if I wanted to loop 10 times, with a starting variable of 3 and incremented 5 each time, I'd do:
for(int i = 3; i <= 53; i+=5) {}
Also, one last thing: please look at variable naming conventions, variables shouldn't start with caps like that, they should be camelCase

How do I update the integer while the loop is running?

When we enter 0 in the program it is supposed to stop running the loop and print the average of the numbers. When I run the program and initially enter 0, the program exits. If I enter in an integer that is not zero first, and then enter 0, the program keeps running and I can't quit.I figure that the integer value needs to update when the user enters a new value for the program to quit, and the sum to be correct.
How do I update the integer value while the loop is running? I should change or add something in the loop I'm guessing.
import java.util.Scanner;
public class Exercise05_01 {
public static void main(String[] args){
float negCount = 0;
float sum = 0;
float posCount = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a positive or negative integer. Entering 0 ends program");
int integer = input.nextInt();
while (integer != 0) {
if (integer > 0) {
posCount = +1;
sum = +integer;
}
if (integer < 0) {
negCount = +1;
sum = +integer;
}
float count = negCount + posCount;
if (integer == 0) {
System.out.println("The answer");
}
}
}
}
There are two problems.
First, you don't get any input while you're in the loop. That's fixable with a suggestion provided earlier by Lunchbox.
Second, this is not accumulating the value:
posCount = +1;
That assigns a positive 1 to posCount every time.
You want to either increment the value...
posCount++;
...or add one explicitly.
posCount += 1;
I think you need to add the line that gets input in your while loop.
while (integer != 0) {
integer = input.nextInt();
.
.
.
This way while the loop is running, every iteration it will check for an input still.
Also I have to say this looks suspiciously like homework... especially the class name...
As Lunchbox points out in his answer, you need to request input from the user from inside your loop, otherwise integer never changes and you never exit your loop; the behaviour you're observing is the program running forever.
The best way to do this is Lunchbox's suggestion:
int integer = input.nextInt();
while(integer != 0){
// Do stuff
integer = input.nextInt();
}
However, you have many other problems with your code. For one thing, why are you using floats to store your counters and sum values? Why not use ints?
For another, you're never actually incrementing those values. As Makoto points out in his answer, the line posCount = +1 is not an increment operator.
In that case, the + operator is the unary plus operator. What this will do is force your signed value to be positive, so +(-1) == 1. While this is useful, it's not what you want to happen, and it's definitely not what you want to be doing around your sum.
Instead, you want to do one of the following three things:
posCount = posCount + 1;
posCount += 1;
posCount++;
Those are all equivalent statements. The ++ operator is the postfix increment operator, which will add 1 to the value of the variable and then return it (It's slightly more complicated than that, but you can read that on your own time). So don't use that syntax for your sum; use one of the other two.

Java recollecting the randomly chosen enums and summing it all up

A mere continuation of this article
Java How to get the sum up all the of the values of each enum
full source code below
http://pastebin.com/VMGUJmeZ
I have this For loop below, and what I am here to ask you guys for today is how I could recollect all of the randomly chosen enums, and sum up all their values.
for (int i = amount; i > 0; --i){//determines the amount of cycles.
Junk randomX = Junk.values()[random.nextInt(Junk.values().length)];
//randomly picks an enum
System.out.println(randomX);
}
Below me is the solution I did which basically declared a int sum, initialize it and put it in the for loop to collect the values of the enums
for (int i = amount; i > 0; --i){
Junk randomX = Junk.values()[random.nextInt(Junk.values().length)];
//randomly picks an enum
System.out.println(randomX);
for(Junk o : Junk.values()){
sum += o.getValue();
//sorry, I had sum declared and initialized outside of the loop.
System.out.println(sum);
}
}
sadly, the output was not desirable
Dresser
0
150
400
650
650
650
...
I understand that I am basically asking others to help me in writing code for me, but I am unsure of how else to do this.
Also I understand it might be impossible to do considering that the only way to get the sum of the enum's value is by doing it outside of the for loop, which will then make the solution impossible as it will only get all of the values.
Perhaps there is something besides a for loop I could use, that someone could recommend me in using.
You have a second loop
for(Junk o : Junk.values()){
sum += o.getValue();
//sorry, I had sum declared and initialized outside of the loop.
System.out.println(sum);
}
which is not neccessary. Simply replace this part by
sum += randomX.getValue();
System.out.println(sum);
int sum = 0;
for (int i = amount; i > 0; --i){
Junk randomX = Junk.values()[random.nextInt(Junk.values().length)];
//randomly picks an enum
System.out.println(randomX);
sum += randomX.getValue();
System.out.println(sum);
}
System.out.println("grand total: " + sum);

Categories

Resources