Bài đăng nổi bật

5.  Exercises on Input, Decision and Loop

5.1  Add2Integer (Input)

Viết chương trình có tên Add2Integers nhắc nhở người dùng nhập hai số nguyên. Chương trình sẽ đọc hai số nguyên như inttính tổng của chúng; và in kết quả. Ví dụ,
Enter first integer: 8
Enter second integer: 9
The sum is: 17
Hints
import java.util.Scanner;   // For keyboard input
/**
 * 1. Prompt user for 2 integers
 * 2. Read inputs as "int"
 * 3. Compute their sum in "int"
 * 4. Print the result
 */
public class Add2Integers {  // Save as "Add2Integers.java"
   public static void main (String[] args) {
      // Declare variables
      int number1, number2, sum;
      Scanner in = new Scanner(System.in);  // Scan the keyboard for input

      // Put up prompting messages and read inputs as "int"
      System.out.print("Enter first integer: ");  // No newline for prompting message
      number1 = in.nextInt();                     // Read next input as "int"
      ......

      // Compute sum
      sum = ......

      // Display result
      System.out.println("The sum is: " + sum);   // Print with newline
      in.close();  // Close Scanner
   }
}

5.2  SumProductMinMax3 (Arithmetic & Min/Max)

Viết chương trình có tên SumProductMinMax3nhắc nhở người dùng cho ba số nguyên. Chương trình sẽ đọc các đầu vào như inttính tổng, tích, tối thiểu và tối đa của ba số nguyên; và in kết quả. Ví dụ như,
Enter 1st integer: 8
Enter 2nd integer: 2
Enter 3rd integer: 9
The sum is: 19
The product is: 144
The min is: 2
The max is: 9
Hints
      // Declare variables
      int number1, number2, number3;  // The 3 input integers
      int sum, product, min, max;     // To compute these
      Scanner in = new Scanner(System.in);  // Scan the keyboard
      
      // Prompt and read inputs as "int"
      ......
      
      // Compute sum and product
      sum = ......
      product = ......

      // Compute min
      // The "coding pattern" for computing min is:
      // 1. Set min to the first item
      // 2. Compare current min with the second item and update min if second item is smaller
      // 3. Repeat for the next item
      min = number1;        // Assume min is the 1st item
      if (number2 < min) {  // Check if the 2nd item is smaller than current min
         min = number2;     // Update min if so
      }
      if (number3 < min) {  // Continue for the next item
         min = number3;
      }
      
      // Compute max - similar to min
      ......
      
      // Print results
      ......
    Thử
    1. Viết chương trình gọi là SumProductMinMax5nhắc nhở người dùng cho năm số nguyên. Chương trình sẽ đọc các đầu vào như inttính tổng, tích, tối thiểu và tối đa của năm số nguyên; và in kết quả. Sử dụng năm intbiến: number1,, number2..., number5để lưu trữ các đầu vào.
  1. .

5.3  CircleComputation (double & printf())

Viết chương trình có tên CircleComputationnhắc nhở người dùng về bán kính hình tròn theo số dấu phẩy động. Chương trình sẽ đọc đầu vào như doubletính đường kính, chu vi và diện tích hình tròn trong doublevà in các giá trị được làm tròn đến 2 chữ số thập phân. Sử dụng hằng số Math.PIdo hệ thống cung cấp cho pi. Các công thức là:
diameter = 2.0 * radius;
area = Math.PI * radius * radius;
circumference = 2.0 * Math.PI * radius;
Hints
      // Declare variables
      double radius, diameter, circumference, area;  // inputs and results - all in double
      ......

      // Prompt and read inputs as "double"
      System.out.print("Enter the radius: ");
      radius = in.nextDouble();  // read input as double

      // Compute in "double"
      ......

      // Print results using printf() with the following format specifiers:
      //   %.2f for a double with 2 decimal digits
      //   %n for a newline
      System.out.printf("Diameter is: %.2f%n", diameter);
      ......
Thử
1. Viết chương trình có tên SphereComputationnhắc nhở người dùng radiusvề hình cầu trong số dấu phẩy động. Chương trình sẽ đọc đầu vào như doubletính thể tích và diện tích bề mặt của quả cầu trong doublevà in các giá trị được làm tròn đến 2 chữ số thập phân. Các công thức là:

surfaceArea = 4 * Math.PI * radius * radius; volume = 4 /3 * Math.PI * radius * radius * radius; // But this does not work in programming?! Why?

2. Lưu ý rằng bạn không thể đặt tên biến surface areabằng dấu cách hoặc surface-areadấu gạch ngang. Quy ước đặt tên của Java là surfaceAreaCác ngôn ngữ khác đề nghị surface_areavới một dấu gạch dưới.

3. Viết chương trình có tên CylinderComputationnhắc nhở người dùng cho cơ sở radiusvà heightcủa hình trụ theo số dấu phẩy động. Chương trình sẽ đọc các đầu vào như doubletính diện tích cơ sở, diện tích bề mặt và thể tích của hình trụ; và in các giá trị được làm tròn đến 2 chữ số thập phân. Các công thức là:


baseArea = Math.PI * radius * radius; surfaceArea = 2.0 * Math.PI * radius + 2.0 * baseArea; volume = baseArea * height;

5.4  Swap2Integers

Viết chương trình có tên Swap2Integersnhắc nhở người dùng cho hai số nguyên. Chương trình sẽ đọc các đầu vào là int, lưu trong hai biến được gọi number1và number2hoán đổi nội dung của hai biến; và in kết quả. Ví dụ như,
Enter first integer: 9
Enter second integer: -9
After the swap, first integer is: -9, second integer is: 9
Gợi ý
Để hoán đổi nội dung của hai biến xvà y, bạn cần giới thiệu một bộ lưu trữ tạm thời, nói tempvà làm : temp ⇐ xx ⇐ yy ⇐ temp.

5.5  IncomeTaxCalculator (Decision)

Thuế suất thuế thu nhập lũy tiến được quy định như sau:
Taxable IncomeRate (%)
First $20,0000
Next $20,00010
Next $20,00020
The remaining30
Ví dụ, giả sử rằng thu nhập chịu thuế là $85000, thuế thu nhập phải nộp là $20000*0% + $20000*10% + $20000*20% + $25000*30%.
Viết một chương trình được gọi là IncomeTaxCalculatorđọc thu nhập chịu thuế (in int). Chương trình sẽ tính thuế thu nhập phải nộp (bằng double); và in kết quả làm tròn đến 2 chữ số thập phân. Ví dụ như,
Enter the taxable income: $41234
The income tax payable is: $2246.80

Enter the taxable income: $67891
The income tax payable is: $8367.30

Enter the taxable income: $85432
The income tax payable is: $13629.60

Enter the taxable income: $12345
The income tax payable is: $0.00
Hints
      // Declare constants first (variables may use these constants)
      // The keyword "final" marked these as constant (i.e., cannot be changed).
      // Use uppercase words joined with underscore to name constants
      final double TAX_RATE_ABOVE_20K = 0.1;
      final double TAX_RATE_ABOVE_40K = 0.2;
      final double TAX_RATE_ABOVE_60K = 0.3;

      // Declare variables
      int taxableIncome;
      double taxPayable;
      ......

      // Compute tax payable in "double" using a nested-if to handle 4 cases
      if (taxableIncome <= 20000) {         // [0, 20000]
         taxPayable = ......;
      } else if (taxableIncome <= 40000) {  // [20001, 40000]
         taxPayable = ......;
      } else if (taxableIncome <= 60000) {  // [40001, 60000]
         taxPayable = ......;
      } else {                              // [60001, ]
         taxPayable = ......;
      }
      // Alternatively, you could use the following nested-if conditions
      // but the above follows the table data
      //if (taxableIncome > 60000) {          // [60001, ]
      //   ......
      //} else if (taxableIncome > 40000) {   // [40001, 60000]
      //   ......
      //} else if (taxableIncome > 20000) {   // [20001, 40000]
      //   ......
      //} else {                              // [0, 20000]
      //   ......
      //}

      // Print results rounded to 2 decimal places
      System.out.printf("The income tax payable is: $%.2f%n", ...);
Thử
Giả sử rằng một 10%khoản giảm thuế được thông báo cho thuế thu nhập phải nộp, giới hạn $1,000, sửa đổi chương trình của bạn để xử lý khoản giảm thuế. Ví dụ, giả sử rằng số thuế phải nộp là $12,000, giảm giá là $1,000, như 10%của $12,000quá nắp.

5.6  IncomeTaxCalculatorWithSentinel (Decision & Loop)

Dựa trên bài tập trước, hãy viết một chương trình được gọi IncomeTaxCalculatorWithSentinelsẽ lặp lại phép tính cho đến khi người dùng nhập -1Ví dụ,
Enter the taxable income (or -1 to end): $41000
The income tax payable is: $2200.00

Enter the taxable income (or -1 to end): $62000
The income tax payable is: $6600.00

Enter the taxable income (or -1 to end): $73123
The income tax payable is: $9936.90

Enter the taxable income (or -1 to end): $84328
The income tax payable is: $13298.40

Enter the taxable income: $-1
bye!
Giá trị -1được gọi là giá trị sentinel . (Wiki: Trong lập trình, giá trị sentinel , còn được gọi là giá trị cờ, giá trị chuyến đi, giá trị giả mạo, giá trị tín hiệu hoặc dữ liệu giả, là một giá trị đặc biệt sử dụng sự hiện diện của nó làm điều kiện chấm dứt.)
Gợi ý
Mẫu  để xử lý đầu vào với giá trị sentinel như sau:
      // Declare constants first
      final int SENTINEL = -1;    // Terminating value for input
      ......

      // Declare variables
      int taxableIncome;
      double taxPayable;
      ......

      // Read the first input to "seed" the while loop
      System.out.print("Enter the taxable income (or -1 to end): $");
      taxableIncome = in.nextInt();

      while (taxableIncome != SENTINEL) {
         // Compute tax payable
         ......
         // Print result
         ......

         // Read the next input
         System.out.print("Enter the taxable income (or -1 to end): $");
         taxableIncome = in.nextInt();
            // Repeat the loop body, only if the input is not the SENTINEL value.
            // Take note that you need to repeat these two statements inside/outside the loop!
      }
      System.out.println("bye!");
Hãy lưu ý rằng chúng tôi lặp lại các câu lệnh đầu vào bên trong và bên ngoài vòng lặp. Lặp đi lặp lại tuyên bố KHÔNG phải là một thực hành lập trình tốt. Điều này là do nó dễ lặp lại (Cntl-C / Cntl-V), nhưng khó duy trì và đồng bộ hóa các câu lệnh lặp lại. Trong trường hợp này, chúng tôi không có lựa chọn nào tốt hơn!

5.7  PensionContributionCalculator (Decision)

Cả người sử dụng lao động và người lao động đều được ủy thác đóng góp một tỷ lệ phần trăm nhất định tiền lương của nhân viên vào quỹ hưu trí của nhân viên. Tỷ lệ được lập bảng như sau:
Employee's AgeEmployee Rate (%)Employer Rate (%)
55 and below2017
above 55 to 601313
above 60 to 657.59
above 6557.5
Tuy nhiên, sự đóng góp phải chịu mức trần của $6,000Nói cách khác, nếu một nhân viên kiếm được $6,800, chỉ $6,000thu hút sự đóng góp của nhân viên và chủ nhân, thì phần còn lại $800thì không.
Viết một chương trình được gọi là PensionContributionCalculatorđọc mức lương hàng tháng và tuổi (trong int) của một nhân viên. Chương trình của bạn sẽ tính toán nhân viên, người sử dụng lao động và tổng đóng góp (trong double); và in kết quả làm tròn đến 2 chữ số thập phân. Ví dụ như,
Enter the monthly salary: $3000
Enter the age: 30
The employee's contribution is: $600.00
The employer's contribution is: $510.00
The total contribution is: $1110.00
Hints
      // Declare constants
      final int SALARY_CEILING = 6000;
      final double EMPLOYEE_RATE_55_AND_BELOW = 0.2;
      final double EMPLOYER_RATE_55_AND_BELOW = 0.17;
      final double EMPLOYEE_RATE_55_TO_60 = 0.13;
      final double EMPLOYER_RATE_55_TO_60 = 0.13;
      final double EMPLOYEE_RATE_60_TO_65 = 0.075;
      final double EMPLOYER_RATE_60_TO_65 = 0.09;
      final double EMPLOYEE_RATE_65_ABOVE = 0.05;
      final double EMPLOYER_RATE_65_ABOVE = 0.075;

      // Declare variables
      int salary, age;     // to be input
      int contributableSalary;
      double employeeContribution, employerContribution, totalContribution;
      ......

      // Check the contribution cap
      contributableSalary = ......
      
      // Compute various contributions in "double" using a nested-if to handle 4 cases
      if (age <= 55) {         // 55 and below
         ......
      } else if (age <= 60) {  // (60, 65]
         ......
      } else if (age <= 65) {  // (55, 60]
         ......
      } else {                 // above 65
         ......
      }
      // Alternatively,
      //if (age > 65) ......
      //else if (age > 60) ......
      //else if (age > 55) ......
      //else ......

5.8  PensionContributionCalculatorWithSentinel (Decision & Loop)

Dựa trên trước đó PensionContributionCalculator, hãy viết một chương trình được gọi là PensionContributionCalculatorWithSentinelsẽ lặp lại các phép tính cho đến khi người dùng nhập -1 cho mức lương. Ví dụ như,
Enter the monthly salary (or -1 to end): $5123
Enter the age: 21
The employee's contribution is: $1024.60
The employer's contribution is: $870.91
The total contribution is: $1895.51

Enter the monthly salary (or -1 to end): $5123
Enter the age: 64
The employee's contribution is: $384.22
The employer's contribution is: $461.07
The total contribution is: $845.30

Enter the monthly salary (or -1 to end): $-1
bye!
Hints
      // Read the first input to "seed" the while loop
      System.out.print("Enter the monthly salary (or -1 to end): $");
      salary = in.nextInt();

      while (salary != SENTINEL) {
         // Read the remaining
         System.out.print("Enter the age: ");
         age = in.nextInt();

         ......
         ......
         
         // Read the next input and repeat
         System.out.print("Enter the monthly salary (or -1 to end): $");
         salary = in.nextInt();
      }

5.9  SalesTaxCalculator (Decision & Loop)

Thuế doanh thu 7%được đánh vào tất cả hàng hóa và dịch vụ được tiêu thụ. Điều bắt buộc là tất cả các thẻ giá phải bao gồm thuế bán hàng. Ví dụ: nếu một mặt hàng có thẻ giá $107, giá thực tế là $100và $7đi đến thuế bán hàng.
Viết chương trình sử dụng vòng lặp để liên tục nhập giá đã bao gồm thuế (tính bằng double); tính giá thực tế và thuế bán hàng (bằng double); và in kết quả làm tròn đến 2 chữ số thập phân. Chương trình sẽ chấm dứt để đáp ứng với đầu vào của -1và in tổng giá, tổng giá thực tế và tổng thuế bán hàng. Ví dụ như,
Enter the tax-inclusive price in dollars (or -1 to end): 107
Actual Price is: $100.00, Sales Tax is: $7.00

Enter the tax-inclusive price in dollars (or -1 to end): 214
Actual Price is: $200.00, Sales Tax is: $14.00

Enter the tax-inclusive price in dollars (or -1 to end): 321
Actual Price is: $300.00, Sales Tax is: $21.00

Enter the tax-inclusive price in dollars (or -1 to end): -1
Total Price is: $642.00
Total Actual Price is: $600.00
Total Sales Tax is: $42.00
Hints
      // Declare constants
      final double SALES_TAX_RATE = 0.07;
      final int SENTINEL = -1;        // Terminating value for input
      
      // Declare variables
      double price, actualPrice, salesTax;  // inputs and results
      double totalPrice = 0.0, totalActualPrice = 0.0, totalSalesTax = 0.0;  // to accumulate
      ......

      // Read the first input to "seed" the while loop
      System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
      price =  in.nextDouble();

      while (price != SENTINEL) {
         // Compute the tax
         ......
         // Accumulate into the totals
         ......
         // Print results
         ......

         // Read the next input and repeat
         System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
         price =  in.nextDouble();
      }
      // print totals
      ......

5.10  ReverseInt (Loop with Modulus/Divide)

Viết chương trình nhắc người dùng về số nguyên dương. Chương trình sẽ đọc đầu vào như intvà in "đảo ngược" của số nguyên đầu vào. Ví dụ như,
Enter a positive integer: 12345
The reverse is: 54321
Hints
Sử dụng mẫu mã sau đây sử dụng vòng lặp while với các hoạt động mô đun / phân chia lặp lại để trích xuất và thả chữ số cuối của số nguyên dương.
      // Declare variables
      int inNumber;   // to be input
      int inDigit;    // each digit
      ......

      // Extract and drop the "last" digit repeatably using a while-loop with modulus/divide operations
      while (inNumber > 0) {
         inDigit = inNumber % 10; // extract the "last" digit
         // Print this digit (which is extracted in reverse order)
         ......
         inNumber /= 10;          // drop "last" digit and repeat
      }
      ......

5.11  SumOfDigitsInt (Loop with Modulus/Divide)

Viết chương trình nhắc người dùng về số nguyên dương. Chương trình sẽ đọc đầu vào như inttính toán và in tổng của tất cả các chữ số của nó. Ví dụ như,
Enter a positive integer: 12345
The sum of all digits is: 15
Hints
See "ReverseInt".

5.12  InputValidation (Loop with boolean flag)

Chương trình của bạn thường cần xác thực các đầu vào của người dùng, ví dụ: các dấu sẽ nằm trong khoảng từ 0 đến 100.
Viết chương trình nhắc người dùng cho một số nguyên giữa 0-10hoặc 90-100Chương trình sẽ đọc đầu vào như intvà lặp lại cho đến khi người dùng nhập một đầu vào hợp lệ. Ví dụ như,
Enter a number between 0-10 or 90-100: -1
Invalid input, try again...
Enter a number between 0-10 or 90-100: 50
Invalid input, try again...
Enter a number between 0-10 or 90-100: 101
Invalid input, try again...
Enter a number between 0-10 or 90-100: 95
You have entered: 95
Hints
Sử dụng mẫu mã sau đây sử dụng vòng lặp do-while được điều khiển bởi booleancờ để xác thực đầu vào. Chúng ta sử dụng vòng lặp do-while thay vì vòng lặp while-do vì chúng ta cần thực thi phần thân để nhắc và xử lý đầu vào ít nhất một lần.
      // Declare variables
      int numberIn;      // to be input
      boolean isValid;   // boolean flag to control the loop
      ......
      
      // Use a do-while loop controlled by a boolean flag 
      // to repeatably read the input until a valid input is entered
      isValid = false;   // default assuming input is not valid
      do {
         // Prompt and read input
         ......

         // Validate input by setting the boolean flag accordingly
         if (numberIn ......) {
            isValid = true;   // exit the loop
         } else {
            System.out.println(......);  // Print error message and repeat
         }
      } while (!isValid);
      ......

5.13  AverageWithInputValidation (Loop with boolean flag)

Viết chương trình nhắc người dùng đánh dấu (giữa 0-100in int) của 3 sinh viên; tính trung bình (tính bằng double); và in kết quả được làm tròn đến 2 chữ số thập phân. Chương trình của bạn cần thực hiện xác nhận đầu vào. Ví dụ như,
Enter the mark (0-100) for student 1: 56
Enter the mark (0-100) for student 2: 101
Invalid input, try again...
Enter the mark (0-100) for student 2: -1
Invalid input, try again...
Enter the mark (0-100) for student 2: 99
Enter the mark (0-100) for student 3: 45
The average is: 66.67
Hints
      // Declare constant
      final int NUM_STUDENTS = 3;
      
      // Declare variables
      int numberIn;
      boolean isValid;   // boolean flag to control the input validation loop
      int sum = 0;
      double average;
      ......
      
      for (int studentNo = 1; studentNo <= NUM_STUDENTS; ++studentNo) {
          // Prompt user for mark with input validation
          ......
          isValid = false;   // reset assuming input is not valid
          do {
             ......
          } while (!isValid);

          sum += ......;
      }
      ......

Post a Comment

Mới hơn Cũ hơn