Tuesday, July 28, 2009

Java prablom?

i just started the java course





the techer want us to do a program shows the letter of the grade that you gate in the test








this is the program





import java.util.Scanner;





public class grade


{


public static void main( String arg[] )


{


Scanner input = new Scanner ( System.in );


int g ;


System.out.print( "Enter your grade please:" );


g = input.nextInt();





if ( g %26lt;= 49 )


System.out.printf ( " F ");





if ( g %26gt;=50 )


System.out.printf ( " C ");





if ( g %26gt;=66 )


System.out.printf ( " B ");





if ( g %26gt;= 81 )


System.out.printf ( " A ");





if ( g %26gt;= 96 )


System.out.printf ( " A+ ");








}








}














the prablom is that when you put a grade like 69 it will show you C B


it should show only C but 69 also works for C condition so what should i do

Java prablom?
There is a big difference between "if" and "else if". An if statement will always be executed where as, an "else if" will only be executed when the if returns false. For instance.





if (1 %26lt; 2)


System.out.printf ( "True! ");


if (2 %26lt; 3)


System.out.printf ( "True! ");





This will print "True! True! ", where as:





if (1 %26lt; 2)


System.out.printf ( "True! ");


else if (2 %26lt; 3)


System.out.printf ( "True! ");





This will only print "True! "





Get the idea? Now apply it to your project.
Reply:You can either use nested if


if ( g %26lt;= 49 ) {


System.out.printf ( " F ");


} else {


if ( g %26gt;=50 )


System.out.printf ( " C ");


}





or





Change the test to include an upper and lower range.


if ( g %26gt;= 0 %26amp;%26amp; g %26lt;= 49 )


System.out.printf ( " F ");
Reply:First, its good habit to use brackets around your If statement. (the way you did it, does works, but other way is more common in programing).





Second you need to use it IF Else statement. Also I would start from the highest and work your way down.





if ( g %26gt;= 96 )


{


System.out.printf ( " A+ ");


}


else if ( g %26gt;= 81 )


{


System.out.printf ( " A ");


}


else if .....





this way once you hit the correct grade it drops out of checking the rest.
Reply:The logic is wrong.





Read through it as if the score was 85.





It reaches the "g %26lt;= 49" line and that is False.





It reaches "g %26gt;= 50" line and that is True.





The result is "C".





What you've done is do a series of greater-than-or-equals checks out of order. Reorder them backwards, and it will work.





Edit:


Actually, more needs to be done. Use ElseIf as well.

artificial flowers

No comments:

Post a Comment