Home > JAVA > ภาษาจาวา while loop

ภาษาจาวา while loop

January 23, 2010 No Comments

While loop ในภาษาจาวานั้นก็คล้ายกับในภาษาซี while loop นั้นใช้ในการทำซ้ำของโปรแกรมโดยมีการกำหนดเงื่อนไขในการที่จะหยุดทำ ในภาษาจาวานั้นจะมีรูปแบบนั้นนี้
while (expression) {
statement(s)
}
โดยในส่วน expression จะเป็นเงื่อนไข ส่วน statement จะเป็นชุดคำสั่ง และจะทำคำสั่งเดียวใต้คำสั่ง while ถ้าหากไม่มีเครื่องหมาย {}
ตัวอย่างโปรแกรม ภาษาจาวาที่ใช้ while loop

public class WhileDemo
{
public static void main(String[] args)
{
String copyFromMe = "Copy this string until you ";
StringBuffer copyToMe = new StringBuffer();

int i = 0;
char c = copyFromMe.charAt(i);

while(c!='g')
{
copyToMe.append(c);
c = copyFromMe.charAt(++i);
}
System.out.println(copyToMe);
}
}

ในโปรแกรมนี้ เริ่มแรกก็มีตัวแปรเก็บข้อความไว้อยู่จะนั้นก็มีตัวแปรประเภท string อีกตัวหนึ่งโดยเริ่มเก็บตัวแรกของข้อความที่เก็บในตัวแปร copyFromMe จากนั้นก็จะตรวจสอบเงื่อนไขในลูป while โดยมีเงื่อนไขคือ c!=’g’ ซึ่งก็คือ ตัวแปร c จะไม่มีค่าเท่ากับตัว g เท่านั้นจะทำใน while loop จะนั้นเมื่อเข้าไปทำในลูปก็จะ เพิ่มค่าตัวอักษรในตัวแปร copyToMe จะใช้ method append ซึ่งจะนำตัวอักษรมาต่อกันซึ่งจะได้ผลลัพธ์นั้นนี้

java while loop

Tags: , , , ,

Tags: JAVA loop while loop จาวา ภาษาจาวา



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>