2015年8月28日 星期五

Java 迴圈語法

Java 迴圈語法:while 、do/while 、for 迴圈

While 迴圈簡單範例:
public class TaxDemo{

 public static void main(String[] args){

  double balance = 500;
  double taxRate = 0.07;
  int years = 0;
  
  while (balance <= 1000){
  
   balance = (balance * (1+0.07));
   years++;
  
  }
  System.out.printf("Year %d: %.2f",years,balance);
 }
} 

修改一下 Elevator 的程式:(其他部份,請參考這裡!)
public class Elevator{
...omit....

//判斷是否到達所須要的樓層
 public void goToFloor(int desiredFloor){
  while (this.currentFloor != desiredFloor){
   if (this.currentFloor > desiredFloor){
    this.goDown();
   } else {
    this.goUp();
   }
  }
  System.out.println("Arrived..");
  this.openDoor();
 }

..... omit ......


執行的程式也一併修改一下:
import java.util.Scanner;

public class ElevatorDemo{

 public static void main(String[] args){
 
  Elevator myElevator = new Elevator();
  Scanner scanner = new Scanner(System.in);
  
  System.out.print("請選擇樓層(1~10):");
  myElevator.doorOpen = true;
  myElevator.goToFloor(scanner.nextInt()); 
  
 }
}


for 迴圈用法:(99乘法表)
public class table99{

 public static void main(String[] args){
 
  for (int i = 1,j = 1; i < 10 ; i=(j==9)?(i+1):(i),j=(j==9)?(1):(j+1)){
   System.out.printf("%d*%d=%d\t",i,j,(i*j));
   if (j==9){
    System.out.println();
   }
  }
 }
}

continue 與 break 也來湊熱鬧:
import java.util.*;

public class ScoreClassDemo{

 public static void main(String[] args){
 
  Scanner scanner = new Scanner(System.in);
  ArrayList pass = new ArrayList();
  ArrayList noPass = new ArrayList();
  
  int account = 0;
  int score = 0;
  
  while (true){
   System.out.printf("請輸入第 %d 位學生成績:",(account + 1));
   score = scanner.nextInt();
   if ((score > 100)||(score <= -2)){
    System.out.println("重新輸入");
    continue;
   } else if (score == -1){
    break;
   } else if ( score >= 60){
    pass.add(score);
   } else {
    noPass.add(score);
   }
   account++;
  }
  System.out.println("及格人數: " + pass.size());
 }
}