Java 9.while语句
生活随笔
收集整理的這篇文章主要介紹了
Java 9.while语句
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
while語句
while語句就是一種循環語句,像if語句一樣計算布爾值表達式的值,并在其值為true時執行一條語句(稱為循環體).但while會在循環體執行完畢后再次計算表達式的值,這一點與if語句不同。
?
1 import java.text.DecimalFormat; 2 import java.util.Scanner; 3 4 public class Average{ 5 6 public static void main(String[] args){ 7 int sum = 0, value, count = 0; 8 double average; 9 10 Scanner scan = new Scanner(System.in); 11 12 System.out.print("Enter an integer (0 to quit): "); 13 value = scan.nextInt(); 14 15 while (value != 0) { 16 17 count++; 18 19 sum += value; 20 System.out.println("The sum so far is " + sum); 21 22 System.out.print("Enter an integer (0 to quit): "); 23 value = scan.nextInt(); 24 } 25 26 System.out.println (); 27 28 if (count == 0) 29 System.out.println("No values were entered."); 30 else{ 31 average = (double)sum / count; 32 33 DecimalFormat fmt = new DecimalFormat("0.###"); 34 System.out.println("The average is " + fmt.format(average)); 35 } 36 } 37嵌套循環
一個循環體中可能包含另一個循環,稱為嵌套循環。
1 import java.util.Scanner; 2 3 public class PalindromeTester 4 { 5 public static void main(String[] args) 6 { 7 String str, another = "y"; 8 int left, right; 9 10 Scanner scan = new Scanner(System.in); 11 12 while (another.equalsIgnoreCase("y")) 13 { 14 System.out.println("Enter a potential palindrome:"); 15 str = scan.nextLine(); 16 17 left = 0; 18 right = str.length() - 1; 19 20 while (str.charAt(left) == str.charAt(right) && left < right) 21 { 22 left++; 23 right--; 24 } 25 26 System.out.println(); 27 28 if (left < right) 29 System.out.println("That string is NOT a palindrome."); 30 else 31 System.out.println("That string IS a palindrome."); 32 33 System.out.println(); 34 System.out.print("Test another palindrome (y/n)? "); 35 another = scan.nextLine(); 36 } 37 } 38 } 39?
轉載于:https://www.cnblogs.com/H97042/p/10925557.html
總結
以上是生活随笔為你收集整理的Java 9.while语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 树——通用树结点数目、高度和度数的实现
- 下一篇: RabbitMQ配置环境变量后启动不了的