Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

why it doesn't go into the if statement?

  Asked By: Chisisi    Date: May 08    Category: Java    Views: 567

import cs1.Keyboard;
public class wenjuan {
public static void main(String[] args) {
int count=1;
int n=Keyboard.readInt();
int total=1;
int halfcount=count/2;
double cos1=0;
if (count%2==0)
for (int i=1; i<count; i++)
for (int j=1;j<halfcount; j++)
if (j%2==0)
cos1+= 1/total;
cos1+= (-1)/total;





The cosine function can be approximated as the summation of an infinite
series. For example,
Complete the program below to use the first n terms of the above series to
approximate and print cos(1). Note that n!=1?2?3???n and 0!=1. You must use
at least one while loop. The only method from the Math class that you may
invoke is pow. All code should be written within method main.
Hint: Decompose the problem! Here are some (not all) of the tasks that the
program needs to perform:
? Accumulate terms in a sequence
? Calculate the factorial of a number
? Generate alternating signs (think about powers of ¨C1)



2 Answers Found

Answer #1    Answered By: Gorkem Yilmaz     Answered On: May 08

Because you have a carrage return after the if(j%2==0) instead of the
following line.

these are good examples of if statements:

if (something) doStuff();

if (something){
} else {

These are dangerous examples:

if (something)

if (something) doStuff;
else doOtherStuff();

Now why are the second lot more dangerous the the first lot?

Well basicly they have less chance to be magicaly broken during the
coding process. If we changed ...

if (something)


if (something)


it won't work because of the extra carrage return.

Errors like that are realy hard to find in large code ... or even small
code when youa re first starting.

As messy as it looks at first I would always recommend new coders to
always put blocks around a if statement  ... even if it is only one thing
they are putting in the if statement.
if (something) {

This leads to good coding practices and it leads to less mistakes.

Answer #2    Answered By: May Hansen     Answered On: May 08

I assume you're asking why it doesn't go into the second IF statement  (i.e. the
"if (j%2==0)" one)?

You're calculating "halfcount" in the wrong place. It gets set to zero and
stays there. The FOR loop with "j" as its control variable therefore never runs
and you never reach that IF statement at all.

Didn't find what you were looking for? Find more on why it doesn't go into the if statement? Or get search suggestion and latest updates.