Why is my increment not being calculated right? - java

I've got a for-loop running, and it asks them for the increment number. But when it outputs the table, it actually doubles the increment. So if I put in 10 for incr it will go up by 20. Please help?
for (double x = fah1; x <= fah2; x+=incr) {
double cel = 5/9.0 * (x-32);
if (x <= 99){
System.out.println(x + " " + df.format(cel);
x+= incr;
}
else {
System.out.println(x + " " + df.format(cel));
x+=incr;
}
}

You are incrementing twice per loop, once in either the if or else, and again at the end in the third statement of the for loop declaration.
Remove the increments in the if and else and rely on the one in the for loop declaration.

You are incrementing twice - once in the for loop declaration and once in the if-then-else statement:
Try changing it to this:
for (double x = fah1; x <= fah2; x+=incr) {
double cel = 5/9.0 * (x-32);
if (x <= 99){
System.out.println(x + " " + df.format(cel);
// Remove the increment from here
}
else
{
System.out.println(x + " " + df.format(cel));
// Remove the increment from here
}
}

Related

How can I limit the number of times a message is displayed while in a for loop in java?

The maximum number of rows that can be displayed for for loop statements is 11, regardless of reaching or exceeding the maximum value for the table.
for (double i = initialvalue; i <= finalvalue; i = i + increase) {
System.out.println(tablevalue + "*" + i + "=" + tablevalue * i);
}
I tried to limit it changing 'finalvalue' to 11 but that doesn't work and I get stuck, someone may can help me please?
Your loop looks fine. Please double check if i gets increased in each loop.
If you just want to reduce the number of outputs but still iterate the full length just use a variable to check for the number of outputs:
int maxOutputs = 11;
for (double i = initialvalue; i <= finalvalue; i = i + increase) {
if(maxOutputs > 0){
System.out.println(tablevalue + "*" + i + "=" + tablevalue * i);
maxOutputs--;
}
}

Rolling dice project: code gives out of bounds exception below 7 and fails to save the first "Die Number"

I understand what out of bounds exception means, and how it happens, but I can't find out why it's happening in my code. Also, the output "Count for side 1" always states 0. This is my first post, but I think I am posting this right.
This is where I think the problem is.
System.out.println("Now rolling " + chosenRollNumber + " times. ");
int[] count = new int[chosenRollNumber];
for (x = 0; x < chosenRollNumber; x++) {
dieNumber = RNG(randomNum, min, max);
System.out.println("dieNumber " + dieNumber);
count[dieNumber]++;
}
System.out.println("Done rolling all dice");
for(x = 0; x < numberOfSides; x++) {
System.out.println("Count for side " + (x + 1) + " is " + count[x]); }
while(true) {
Method RNG(randomNum, min, max) is expected to return values in the range [min...max] (inclusive), while dieNumber as the index in count array needs to be in the range [0; numberOfSides), and the following relation exists numberOfSides == max - min + 1.
So, a correction is needed to transform dieNumber into a valid index:
System.out.println("Now rolling " + chosenRollNumber + " times. ");
int[] count = new int[numberOfSides];
for (x = 0; x < chosenRollNumber; x++) {
dieNumber = RNG(randomNum, min, max);
System.out.println("dieNumber " + dieNumber);
int dieIndex = (dieNumber - min) % numberOfSides;
count[dieIndex]++;
}

Reading the "?" and ":" operator in Java [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 3 years ago.
I'm new to Java and while doing some homework I came across this example:
String result = " ";
for (int r = rows(); r >= 0; r++) {
result += ("___") + (r == 0 ? (" ") : ("_"));
}
for (int y = columns(); y >= 0; y++) {
for (int x = 0; x <= rows(); x++) {
result += ("|") + ((located && theLocation(y, x)) ? (youWin + "S"
+ " ") : (" " + (mysterySpot[y][x] == 'S' ? (" ") :
(mysterySpot[y][x])) + " "));
}
If I understand this correctly, the first for-loop should be equivalent to:
for (int r = rows(); r >= 0; r++) {
result += "___";
if (r == 0) {
result += " ";
}
else {
result += "_";
Am I reading it correctly? For the second part, it looks like there's an if-else statement within another if-else statement. This is the part I'm confused about, what would the code look like if I were to write it out as if-else statements?
Translated into ifs and elses, this looks something like the following.
for (int y = columns(); y >= 0; y++) {
for (int x = 0; x <= rows(); x++) {
if (located && theLocation(y,x)) {
result += "|" + youWin + "S ";
} else if (mysterySpot[y][x] == 'S') {
result += "| ";
} else {
result += "| " + mysterySpot[y][x] + " ";
}
}
}
Note that you should almost never use single-letter variable names, and if you do, you should try to make them meaningful. In this particular case, using y for a column number and x for a row number is the complete reverse of what anyone would expect.
Never write code like the code in this book. My best advice would be to learn from a different book.
So the "?" and the ":" are read like this....
If a is less than b put x else put y.
This statement is shown in code here.
if (a < b){
// Does a thing
x;
}else{
// Does a cooler thing
y;
}
Alternatively, we can write it like so...
a < b ? x : y
So the part before the "?" is asking if it is true. If a is indeed greater than b then do x the ":" is the else statement or the alternative
[the question] ? [option1 if true] : [option2 if false]

java: how to find a value in which initial value is zero and getting error "/ by zero"

I need to calculate accuracy in my java game. So far, I tried several methods however, everytime it either doesn't work or gives me an error "/ by zero". The initial value for bullets_shot is zero and the formula for accuracy is enemies_downed % bullets_shot. How can I bypass this error while getting an accurate read for accuracy? I tried doing a loop where it sets bullets_shot to 1 if it is 0 but it wouldn't give an accurate reading. Is there a way in which I can set a value in place for it until it has a value greater than 1 and if so how would I do so? Here are some code snippets.
here is the full code:
https://github.com/ms12r/Galaxy-Monkeys
In the tick method of the enemy class:
if(tempObject.getId() == ID.Bullet)
{
if(getBounds().intersects(tempObject.getBounds()))
{
hp -= 50;
bullets_hit += 1;
handler.removeObject(tempObject);
and in the mouseinput class
for (int i = 0; i < handler.object.size(); i++)
{
GameObject tempObject = handler.object.get(i);
if(tempObject.getId() == ID.Player)
{
handler.addObject(new Bullet(tempObject.getX()+16,
tempObject.getY()+24, ID.Bullet, handler, x, y, game));
bullets_shot += 1;
}
in the game class
System.out.println("GAME OVER");
System.out.println("Level Reached: " + game.level);
System.out.println("Accuracy: " + ((Enemy.bullets_hit + Gorilla.bullets_hit) % MouseInput.bullets_shot) + "%");
Game.INSTANCE.stop(); }
If the error you're getting is / by zero, consider looking at your calculation.
System.out.println("Accuracy: " + ((Enemy.bullets_hit + Gorilla.bullets_hit) % MouseInput.bullets_shot) + "%");
Quite simply, MouseInput.bullets_shot has no check on it to prevent the error from happening.
You can fix it with a simple if statement.
The calculation can only happen without a divide by zero error if (in your case) the user shot some bullets. The case in which no shots were fired could be evaluated as 0 accuracy:
...
double accuracy;
if (MouseInput.bullets_shot > 0) {
// your calculation
accuracy = (Enemy.bullets_hit + Gorilla.bullets_hit) % MouseInput.bullets_shot;
} else {
accuracy = 0D;
}
System.out.println("Accuracy: " + accuracy);
...
One question remains: why modulus (%) instead of division (/) for a percent calculation?
You could create a simple method called bulletAcuracy() like the following
public static double bulletAcuracy(int bulletHits, int totalBulletsFired)
{
if(totalBulletsFired == 0)
return 0;
return bulletHits/((double)totalBulletsFired);
}
Then call it in main like so
System.out.println("Accuracy: " + bulletAcuracy(Enemy.bullets_hit + Gorilla.bullets_hit, MouseInput.bullets_shot) + "%");

Can't seem to figure out why my loop wont progress

I can't seem to figure out why my for loop is not working. I have been on the for about an hour now and the closest I have come is this. I'm trying to find out how many McNuggets you can buy using the 6, 9, and 20 packs. All I need dopeChecker(x) to do is return a true or a false. I haven't implemented check the next number yet because it wont even find that a 6 pack can be bought yet. I know it's in the loop somewhere but I just can't find out where. This is form the MIT open course ware problem 2. I don't know if you guys have seen it but I'm just letting you know this is where I'm getting my info.
int x = 0, y = 0, z = 0;// These will the the pack of McNuggets that we can buy.
int testFor = 0; //This will be the number of McNuggets we are looking for.
int matches = 0; //This will be the number of consecutive matches we will be looking for.
public void dopeEquation(){
while (matches < 6){//It's 6 Because that is the smallest order of nuggets we can buy.
//Looking for smaller nuggets then we can buy would not make sense.
while (testFor < 6){
testFor++;
}
if (dopeChecker(testFor)){
matches++;
} else{
matches = 0;
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
}
}
}
private boolean dopeChecker(int testFor){
for ( x = 0 ; x*6 <= testFor; x++){
for ( y = 0 ; y*9 <= testFor; y++){
for (z = 0 ; z*20 <= testFor;){
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
if (x*6 + y*9 + z*20 == testFor){
matches++;
System.out.println("match");
return true;
}else{
System.out.println("no match");
}
}
}
}
return false;
}
}
The z variable is always 0, you're not changing it.
Your code goes inside the first while loop:
while (matches < 6){
Then increased testFor to 6 with the following code:
while (testFor < 6){
testFor++;
}
Then goes to dopeChecker:
dopeChecker(int testFor)
Then insde the 3rd loop, for z:
for (z = 0 ; z*20 <= testFor;) {
...
}
z is never incremented, so you need to write this as:
for (z = 0 ; z*20 <= testFor; z++){
}
The following is the innermost for loop. I have commented where the problem is. as you can see, z never gets implemented. therefore, the loop will never terminate, as 0 <= testFor, since TestFor >= 6.
for (z = 0 ; z*20 <= testFor;/* incrementor needed here*/){
System.out.println(x + "," + y +"," + z +"," + testFor + "," + matches);
if (x*6 + y*9 + z*20 == testFor){
matches++;
System.out.println("match");
return true;
}else{
System.out.println("no match");
}
}

Categories

Resources