跳轉到內容

Javagony/其他條件和迴圈

來自 Wikibooks,開放的書籍,為開放的世界

其他條件

[編輯 | 編輯原始碼]

我們知道如何在 Javagony 中編寫比較兩個數字的條件。如果我們想要檢查其他條件呢?好吧,這可以透過使用布林變數和函式 Boolean.compare(b1,true) 來完成,其中 b1 是儲存條件結果(true 或 false)的變數。如果布林變數為 true,則返回 0,如果為 false,則返回 -1。因為我們已經知道如何在 Javagony 中檢查一個數字是否為 0,這意味著我們可以檢查任何條件。

public class More
{
   public static void main(String[] args)
   {
      boolean b1=7.5/5>1; //replace with another condition
      
      try
      {
         int temp=Boolean.compare(b1,true);
         temp=1/temp;
         
         System.out.println("Condition is false");
      }
      catch(Exception IO)
      {
         System.out.println("Condition is true");
      }
   }
}

Do/while 迴圈

[編輯 | 編輯原始碼]

現在我們知道如何檢查任何條件是否為真,在 Javagony 中實現 do/while 迴圈的替代方案很容易。我們所需要做的就是建立一個執行某些操作的函式,然後在滿足特定條件時呼叫自身。

為了本書的目的,我們將編寫一段程式碼,列印所有 3 的冪,直到我們到達一個其最低有效位為 7 的數字。它將列印的最後一個數字將是 27。

public class More
{
   public static void main(String[] args)
   {
      loop(1);
   }
   
   public static void loop(int n)
   {
      System.out.println(n);
      boolean b1=n%10==7;
      
      try
      {
         int temp=Boolean.compare(b1,true);
         temp=1/temp;
         
         loop(n*3);
      }
      catch(Exception IO)
      {
         
      }
   }
}

While 迴圈

[編輯 | 編輯原始碼]

While 迴圈的工作原理類似於 do/while,只是這次我們在函式開始時檢查條件,而不是在函式結束時。如果滿足條件,我們將執行程式碼。如果不是,我們將使用 return 語句退出函式。在函式結束時,在執行程式碼後,它將無條件地呼叫自身。

讓我們利用這些知識編寫一段程式碼,接收一個正整數,並列印該數字的所有數字 - 從最低有效位開始,以最高有效位結束。

public class More
{
   public static void main(String[] args)
   {
      loop(1234567890);
   }
   
   public static void loop(int n)
   {
      boolean b1=n<1;
      
      try
      {
         int temp=Boolean.compare(b1,true);
         temp=1/temp;
      }
      catch(Exception IO)
      {
         return;
      }
      
      System.out.println(n%10);
      loop(n/10);
   }
}

如果我們想要函式返回最高有效位呢?好吧,我們可以輕鬆地修改這段程式碼來做到這一點。

public class More
{
   public static void main(String[] args)
   {
      System.out.println(loop(45454365));
   }
   
   public static int loop(int n)
   {
      boolean b1=n<10;
      
      try
      {
         int temp=Boolean.compare(b1,true);
         temp=1/temp;
      }
      catch(Exception IO)
      {
         return n;
      }
      
      return loop(n/10);
   }
}

讓我們修改這段程式碼,返回一個 ArrayList,其中包含該數字的所有數字,從最高有效位開始,以最低有效位結束。

import java.util.ArrayList;

public class More
{
   public static void main(String[] args)
   {
      System.out.println(loop(3874897));
   }
   
   public static ArrayList<Integer> loop(int n)
   {
      boolean b1=n<10;
      
      try
      {
         int temp=Boolean.compare(b1,true);
         temp=1/temp;
      }
      catch(Exception IO)
      {
         ArrayList<Integer> a=new ArrayList<Integer>();
         a.add(n);
         return a;
      }
      
      ArrayList<Integer> a=loop(n/10);
      a.add(n%10);
      return a;
   }
}
華夏公益教科書