案例 - 前多少个正整数的和会超过给定的数?

题目.

用户输入一个整数requiredSum,找出n,使得前n个正整数的和大于requiredSum.

  • 用户输入(requiredSum);
  • 如果用户输入错误整数(0或者负数),要求重新输入;
  • 如果用户尝试次数超过3次,终止程序。

1. 用户只输入整数的情况(尝试理解并复现)

SumAsRequired.java

import java.util.Scanner;

public class SumAsRequired {
	private static final int allowedAttempts = 3;

	public static void main(String[] args) {

		int requiredSum = 0; // 用来存储用户输入的数,默认0,不合法,后面要求输入
		int attempts = 1; // 存储用户已经尝试输入的次数
		
		Scanner scanner = new Scanner(System.in);
		
		// 判断输入是否大于0,如果输不大于0 且 尝试次数允许:要求重新输入
		while (requiredSum <= 0 && attempts <= allowedAttempts) {
			if (attempts == 1)  //第一次输入的提示信息
				System.out.print("Input the required sum (You have 3 chances): ");
			else  //后续输入的提示信息
				System.out.print("You must input a positive integer. Please retry: ");
			
			requiredSum = scanner.nextInt();
			attempts++; // 尝试次数+1
		}
		scanner.close();
		
		// 用完所有尝试次数后(上面的while),输入仍然不正确:终止程序
		if (requiredSum <= 0) { 
			System.out.println("Too many tries. Please have a break.");
			return; // 直接终止main方法
		}

		// 输入的数大于0,开始计算n
		int n; // 定义连续增加的整数
		int sum = 0; // 记录前n个数的和
		for (n = 1; n <= requiredSum; n++) {
			sum += n;
			if (sum > requiredSum)
				break;
		}
        
		System.out.println("\n----------processing-----------"); // 假装在努力
		System.out.printf("\nThe first %d positive integers' sum is greater than %d\n", n, requiredSum);
	}

}

2. 处理用户输入非整数的情况(扩展阅读)

注:此处要用到Java异常处理的机制,以前没有接触过编程的同学可以直接跳过

import java.util.InputMismatchException;
import java.util.Scanner;

public class SumAsRequiredExt {

	private static final int allowedAttempts = 3;

	public static void main(String[] args) {

		int requiredSum = 0; // 用来存储用户输入的数,默认0,不合法,后面要求输入
		int attempts = 1; // 存储用户已经尝试输入的次数

		Scanner scanner = new Scanner(System.in);

		// 判断输入是否大于0,如果输不大于0 且 尝试次数允许:要求重新输入
		while (requiredSum <= 0 && attempts <= allowedAttempts) {
			if (attempts == 1)
				System.out.print("Input the required sum (You have 3 chances): ");
			else
				System.out.print("You must input a positve integer. Please retry: ");

			try{ // 捕获异常
				requiredSum = scanner.nextInt();
			} catch(InputMismatchException e) { //处理输入不是整数的异常
				System.out.println("An integer is required.");
				scanner.nextLine(); // scanner.nextInt()方法不会读换行符,这里读入用户本次后续所有输入,并将光标移动到下个输入的开头
			}
			attempts++; // 尝试次数+1
		}
		scanner.close();

		// 用完所有尝试次数后(上面的while),输入仍然不正确:终止程序
		if (requiredSum <= 0) {
			System.out.println("Too many tries. Please have a break.");
			return; // 直接终止main方法
		}

		// 输入的数大于0,开始计算n
		int n; // 定义连续增加的整数
		int sum = 0; // 记录前n个数的和
		for (n = 1; n <= requiredSum; n++) {
			sum += n;
			if (sum > requiredSum)
				break;
		}

		System.out.println("\n----------processing-----------");
		System.out.printf("\nThe first %d positive integers' sum is greater than %d\n", n, requiredSum);
	}

}