Jana 7.while语句
Posted h97042
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jana 7.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
以上是关于Jana 7.while语句的主要内容,如果未能解决你的问题,请参考以下文章
[AndroidStudio]_[初级]_[配置自动完成的代码片段]