2008年12月1日 星期一

simple java(四)--if-else(1)

條件判斷式
if /else
例一.
import javax.swing.*; //用對話框
public class IsEven2 {
public static void main( String args[] ){
String inStr; //要入既String
int num; //宣告 要入既數
String answer;
inStr = JOptionPane.showInputDialog("Enter a number." );
num = Integer.parseInt( inStr );
if (num % 2 == 0) //如果你輸入的數字..除2.餘數係0
answer = "even"; //答案雙數.
else //不是的話
answer = "odd"; //答案單數.
JOptionPane.showMessageDialog( null,num + " is " + answer + ".", "Results",JOptionPane.PLAIN MESSAGE );
System.exit( 0 ); }}
執行結果:
Enter a number
50
50 is even
else-if
例二.
import javax.swing.*;
public class Bonus {
public static void main( String args[] ) {
String inStr;
int salesAmt, bonus;
inStr = JOptionPane.showInputDialog( "Enter a number." );
salesAmt = Integer.parseInt( inStr );
if ( salesAmt > 1000 ) {
bonus = 5000;}
else if( salesAmt > 800 )
{bonus = 3000;}
else if (salesAmt > 600)
{bonus = 2000;}
else if (salesAmt > 400)
{bonus = 1000;}
else if (salesAmt > 200)
{bonus = 500;}
else
{bonus = 0;}
JOptionPane.showMessageDialog( null,"The bonus is"+ bonus +" .");
System.exit( 0 ); }}
*************************

沒有留言: