why is this do-while calculation is wrong? - java

When I enter 20 for current5, minuteCurrent should be 240, but do part keeps working even if minuteCurrent is over 240. Why? I tried so many more things, but they didn't help.
import java.util.Scanner;
class Person {
String name;
int heartRatePer5;
int current5;
void alarm() {
for (int i = 0; i < 3; i++)
System.out.print("!!! ");
System.out.println();
}
void stopAlarm() {
System.out.println("Alarm stopped");
}
}
public class App{
public static void main(String[] args) {
Person person1 = new Person();
Scanner input = new Scanner(System.in);
System.out.println("Enter the current heart rate per 5 seconds: ");
person1.current5 = input.nextInt();
int minuteCurrent = person1.current5 * 12;
// minuteCurrent = 0;
do {
System.out.println("Normalizing.");
person1.stopAlarm();
//minuteCurrent = input.nextInt();
break;
}
while (minuteCurrent < 220);
}
}

Do while loops work differently than while loops.
Notice the while loop condition is now moved to after the do while
loop body. The do while loop body is always executed at least once,
and is then executed repeatedly while the while loop condition is
true.
See more here.
How can you fix it? Change your while loop to look like this:
while (minuteCurrent < 220) {
System.out.println("Normalizing.");
person1.stopAlarm();
break;
}
Also, I have no idea why you are using a while loop. It would make a lot more sense to just use an if statement - it's the same thing as a while loop with a break at the end.

do part keeps working even if minuteCurrent is over 240
When you say keeps working: I assume you mean: works exactly once.
This is normal; it is a guarantee of do. The statements within the do block are always executed at least once.
Perhaps you want a regular while loop instead?
The inductive case should look like this:
while (minuteCurrent < 220) {
minuteCurrent = input.nextInt();
}
I am unclear what the effect is of person1.stopAlarm();, or how many times you want to print the "Normalizing" message. So this may not be a full fix of your algorithm. But I think switching from a do-while to a regular while loop should fix at least the confusion that you've described.

Related

Java for loop gets skipped - my mistake?

I have already some c# knowledge but I'm really confused by such an easy thing, but maybe the problem is deeper than I expect. I imported a "little game" for learning java and wrote that code:
import de.ur.mi.bouncer.apps.BouncerApp;
public class DasErsteHindernis extends BouncerApp {
#Override
public void bounce() {
loadMap("Obstacles");
runtillwall();
climbupwards();
}
private void runtillwall(){
while(bouncer.canMoveForward() == true){
bouncer.move();
}
}
private void climbupwards(){
bouncer.turnLeft();
bouncer.move();
for(int i = 0; i==2; i++){
bouncer.turnLeft();
}
}
But the for loop gets skipped -> the bouncer doesn't turn left. What did I do wrong?
The middle part of a for loop is a condition. Yours is saying while i is equal to 2, do this. It never gets to two, so it never executes. You should be using the less-than or less-than-or-equal-to sign. (< <=)
for(int i = 0; i==2; i++){
Here you are initializing i with 0,so first when loop starts i is 0 ,then middle part which is condition in your loop that should be true for loop to start.In your case,you are saying if i is equal to 2 then execute the instruction.It fails and your loop body is not executed single time.
it seems you need
for(int i = 0; i<=2; i++){
This one will execute loop body 3 times.
See Also
for loop in Java

Java, repeat If statement if the condition was false

Simplified, I basically have an if statement like this:
if(A[random]==1)
A[random]=0;
else
continue;
Now I know the 'continue' is for loop statements and this won't work, but I wanted something after the else that if indeed the else(basicaly the condition was false) was activated it repeated the first if(A[random]==1) statement.
You can use a while statement instead:
while (A[random] != 1) {
A[random] = 0;
// generate a new random...
}
You can try below recursion code and see if this resolve's your query
public class Test {
public void continueIf(){
if(A[random]==1)
A[random]=0;
else {
continueIf();
}
}
public static void main(String[] args) {
new Test().continueIf();
}
}
Please note if, if condition is not satisfy then it will lead to stackoverflowerror. That too it depends on the size of JVM memory. check this link for more details on stackoverflow error.
The if/Else statement won't work by itself with looping through an array. I suggest sticking it in either a For loop or a While loop. The loop will search the array and the if/else statement will check the index for the condition provided. I would also get rid of else too. You don't really need that part just the if.
A for loop in the most basic example would look something like this:
for(var i = 0; i < SIZE; i++)
{
if (A[i] == 1)
A[i] = 0;
}
SIZE would be the size of your array
random = ...; // get first random number
while (A[random] != 1) {
random = ...; // get new random number
}
A[random] = 0; // now is 1, switch it to 0
This should work.The other answers have described while and recursion so i am
also adding a do while loop.
do{
//generate the random number
}while(A[random]!=1)//The loop iterates till the condition A[random]!=1 is satisfied
A[random]==0;//changing the bit to 0
Please note that if there is no bit =1 in the array then this solution will fail because you are generating indexes randomly.
So if the array has no element =1 then it keeps on checking the indexes repeatedly and generates infinite loop.
Hope it helps.happy coding!!

How do I branch into a specified part of a loop?

int a = 0;
int b = 0;
int c = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
b = sc.nextInt();
a =+ b;
c =+ (a + 1);
if (c < 20) {
i = 2;
}
}
if I have lines numbered from 0 to 6 inside the loop, the loop would be
so if c is less than 20, it repeats the operation "c=+(a+1);" until it breaks out of the loop by c>=20.
this is a simplified code from my program, mine is GUI. every time I run the code, it freezes.
use c+= instead of c=+. try that, cheers!
and b+= instead ofb=+.
You can tag a loop and do break or continue instructions, but you need design the flow, it is not possible to go into specified line, because java don't use goto instruction. You can only switch the flow inside loops by those instructions.
myloopTag:
for (...; ...; ...) {
// and you can break current loop by:
break;
// or specific (outer) loop by
break myloopTag;
// you can also use 'continue' to go to the start of the loop and increment again
continue;
// or to 'continue' at a label:
continue myloopTag;
}
You're probably very new to the language. Welcome!
If I understand your description of your intent properly, you want your code to exit the loop when c>=20. Based on your description of numbering your lines and the fact that you have the statement:
if(c<20){
i=2;
}
it seems that you think that the iterator i in the for loop is related to the line that will be executed*. This is not the case. The iterator i is a variable that simply holds an integer (just like a, b, and c in your code).
I suggest you take a look at a tutorial on for loops. It might be helpful for you to review other language basics as well, like how control flow works (this may be a better one to start with, actually).
*This guess at your intent is further supported by you counting that there are 6 lines and that your loop goes up to 6.

random number generator is generating huge negative numbers

So I am creating a random code that's not necessarily pertinent to anything at this level, but I'm more testing a few ideas. So for some reason my code will work randomly, but for most of the time it's throwing out a random negative number usually in the vicinity of -413796084. I don't know why it's doing this and I am trying to keep the numbers in the vicinity of 0 - 50. I thought I had done it right but obviously I haven't. Also I am relatively new at Java, if that helps explain any mistakes I made.
import java.util.Scanner;
import java.util.Random;
class damagecalc {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
Random randamage = new Random();
int totaldmg;
System.out.println("Will you (a) attack, (s) defend, (d) skip your turn, (f) magic, (i) use an item?");
String dmgString = input.next();
char dmgChar = dmgString.charAt(0);
if(dmgChar == 'a'){
for(int finaldmg=50;finaldmg<=50;finaldmg++){
totaldmg = randamage.nextInt(10);
}
totaldmg = randamage.nextInt();
if(totaldmg >= 50){
System.out.println("You have defeated the monster!");
}else{
System.out.println("Damage Dealt:" + totaldmg);
}
}
}
}
EDIT------------------------------------------------
So I changed my code and fixed some things and now it's just spitting out 0 every time. Maybe now it will be a little easier to figure out. But I definitely need help.
This is the new code:
import java.util.Scanner;
import java.util.Random;
class damagecalc {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
Random randamage = new Random();
int totaldmg;
System.out.println("Will you (a) attack, (s) defend, (d) skip your turn, (f) magic, (i) use an item?");
String dmgString = input.next();
char dmgChar = dmgString.charAt(0);
if(dmgChar == 'a'){
for(int finaldmg=1;finaldmg<=50;finaldmg++){
}
totaldmg = randamage.nextInt(1);
if(totaldmg >= 50){
System.out.println("You have defeated the monster!");
}else{
System.out.println("Damage Dealt:" + totaldmg);
}
}
}
}
totaldmg = randamage.nextInt();
Random.nextInt() can return any legal value for an int, including the massive negative ones, which isn't likely to be the result you want here. Give nextInt some integer as an argument to constrain it to the desired range.
also, I'd take a look at this loop because chances are that it doesn't do what you think it does.
for(int finaldmg=50;finaldmg<=50;finaldmg++){
totaldmg = randamage.nextInt(10);
}
The body of the loop executes only once and totaldmg is overwritten right after the loop anyway.
EDIT: if you want just to generate a number between 0 and 50, you can just replace this:
for(int finaldmg=50;finaldmg<=50;finaldmg++){
totaldmg = randamage.nextInt(10);
}
totaldmg = randamage.nextInt();
with this:
totaldmg = randamage.nextInt(51);
In case you're wondering about that 51, that is the excluded upper bound - meaning that you'll get damage amounts that are at least zero and at most 50.
Sorry my first answer was c#, changed.
What you want is
totaldmg = randamage.nextInt(50);
use 51 if you want it to generate between 0 and 50 since it is exclusive.
Or if you're going for 50+random damage between 0 and 10, use this:
totaldmg = 50 + randamage.nextInt(10);
The other answer pointed out that weird for loop and I really don't know what you're going for anymore
Lol based on your discussion below the other answer, and assuming you don't find the real answer to your problem, if the negative numbers are between 0 and -50 then just use
totaldmg = Math.abs(randamage.NextInt(50));
and if the numbers are still negative and HUGELY negative:
totaldmg = Math.abs(randomage.NextInt(50)) % 50;
Awful, awful fix, but if it's honestly a bug or something this would be about as good in theory
So I figured it out. One I'm an idiot for having my totaldmg = randamage.nextInt(); twice, but when I took out one of them I was only getting 0's. So when I changed it to totaldmg = randamage.nextInt(50) it worked perfectly. Sweet. Thanks everyone for working with me. You all are fantastic individuals.

Average of n numbers in java

Using loop I want to calculate the average of n numbers in Java and when user enters 0 the loop ends.
Here is the code that I have written:
public class start {
public static void main(String[] args) {
System.out.println("Enter an int value, the program exits if the input is 0");
Scanner input = new Scanner (System.in);
int h = 0;
while (input.nextInt() == 0){
int inp = input.nextInt();
int j = inp;
int i = 0;
h = j + i;
break;
}
System.out.println("The total is: "+ h);
}
}
Am I making any logical error?
Don't name the sum h, but sum.
The while-condition is wrong
Why do you use inp and j and i?
There is an unconditional break - why?
You talk about the average. Do you know what the average is?
Your output message is not about average - it is about the sum.
"Am I making any logical error?"
Yes. This looks like a homework problem so I won't spell it out for you, but think about what the value of i is, and what h = j + i means in this case.
You also need to be careful about calling input.nextInt(). What will happen when you call it twice each time through the loop (which is what you are doing)?
Homework, right?
Calling input.nextInt() in the while loop condition and also to fill in int inp means that each trip through the loop is reading two numbers (one of which is ignored). You need to figure out a way to only read one number per loop iteration and use it for both the == 0 comparison as well as for inp.
Additionally, you've done the right thing having h outside the while loop, but I think you're confusing yourself with j and i inside the loop. You might consider slightly more descriptive names--which will make your code much easier to reason about.
You need to keep a counter of how many numbers you read so you can divide the total by this number to get the average.
Edited the while loop:
while(true){
int e=input.nextInt();
if(e==0) break;
h+=e;
numberOfItems++;
}
Your original implementation called nextInt() twice, which has the effect of discarding every other number (which is definitely not what you intended to do).
Assuming that you asking the user only once, to enter and if the number if zero you simply want to display the average. you need a variable declared outside the while loop that will keep adding different numbers entered by the user, along with a second variable which track the number of cases entered by the user and keep incrementing itself by one till number is not zero as entered by the user. And as the user Enters 0, the loop will break and here our Average will be displayed.
import java.util.Scanner;
public class LoopAverage
{
public static void main(String[] args0)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Integer value : ");
int value = -1, sum = 0, count = 0;
while((value = scan.nextInt()) != 0)
{
count++;
sum = sum + value;
}
System.out.println("Average : " + (sum / count));
}
}
Hope that might help,
Regards
yes, oodles of logical errors.
your while loop condition is wrong, you're consuming the first value
you enter and unless that number is 0 you never enter the loop at all
i var has no purpose
you're breaking after one iteration
you're not calculating a running total
you're not incrementing a count for the average dividend
you're not calculating an average
This looks like you threw some code together and posted it. The most
glaring errors would have been found just by attempting to run it.
Some other things to consider:
Make sure to check for divide by 0
If you do an integer division, you might end up with an incorrect
average, as it will be rounded. Best to cast either the divisor or
dividend to a float
variable names should be helpful, get into the habit of using them
I recommend you to refer to the condition of "while" loop: if condition meets, what would the program do?
(If you know a little bit VB, what is the difference between do...until... and do...while...?)
Also, when you call scanner.nextInt(), what does the program do? For each input, how should you call it?
Last but not least, when should you use "break" or "continue"?
For the fundamentals, if you are in a course, recommend you to understand the notes. Or you can find some good books explaining details of Java. e.g. Thinking in Java
Enjoy learning Java.

Categories