使用标记值控制循环:sum,data
1 package com.baidu; 2 import java.util.Scanner; 3 public class SentinelValue { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in);//(Input):只能从中读取数据,而不能向其写入数据 6 7 System.out.print("Enter an unteger (the input ends if it is 0 ): "); 8 int data = input.nextInt();//(Input):只能从中读取数据,而不能向其写入数据 9 10 int sum = 0; 11 while(data != 0) { 12 sum += data; 13 14 System.out.print("Enter an integer (the input ends if it is 0): "); 15 data = input.nextInt();//(Input):只能从中读取数据,而不能向其写入数据 16 } 17 System.out.println("The sum is " + sum); 18 } 19 }