码迷,mamicode.com
首页 > 其他好文 > 详细

Jana 7.while语句

时间:2019-05-26 13:10:41      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:sys   tin   嵌套循环   other   语句   16px   for   als   div   

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  

 

Jana 7.while语句

标签:sys   tin   嵌套循环   other   语句   16px   for   als   div   

原文地址:https://www.cnblogs.com/H97042/p/10925557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!