Provide Best Programming Tutorials

## 编程作业 — Java循环

What is 5 + 9? 12
Wrong answer. Try again. What is 5 + 9? 34 Wrong answer. Try again. What is 5 + 9? 14 You got it!
import java.util.Scanner;

public class GuessNumber {
public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 101);

Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 100");

int guess = -1;
while (guess != number) {
// Prompt the user to guess the number
guess = input.nextInt();

if (guess == number)
System.out.println("Yes, the number is " + number);
else if (guess > number)
else
} // End of loop
}
}

## (统计正教和负数的个数然后计算这些数的平均值）

Enter an integer, the input ends if it is 0: 1 2 -1 3 0
The number of positives is 3 The number of negatives is 1 The total is 5.0
The average is 1.25
import java.util.Scanner;

public class Exercise_05_01 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int positives = 0;  // Count the number of positive numbers
int negatives = 0;  // Count the number of negative numbers
int count = 0;      // Count all numbers
double total = 0;    // Accumulate a totol

// Promopt the user to enter an integer or 0 to exit
System.out.print("Enter an integer, the input ends if it is 0: ");
int number = input.nextInt();

if (number == 0) {  // Test for sentinel value
System.out.println("No numbers are entered except 0");
System.exit(1);
}

while (number != 0) {// Test for sentinel value
if (number > 0) {
positives++;  // Increase positives
} else {
negatives++;  // Increase negatives
}
total += number;  // Accumulate total
count++;        // Increase the count
number = input.nextInt();
}

// Calculate the average
double average = total / count;

// Display results
System.out.println(
"The number of positive is " + positives +
"\nThe number of negatives is " + negatives +
"\nThe total is total " + total +
"\nThe average is " + average);
}
}

## (将千克转换成磅）编写程序，显示下面的表格（注意：1 千克为2.2 磅）

/*
(Conversion from kilograms to pounds) Write a program that displays the following
table (note that 1 kilogram is 2.2 pounds):
Kilograms     Pounds
1                2.2
3                6.6
...
197            433.4
199            437.8
*/
public class Exercise_05_02 {

public static void main(String[] args) {
final double POUNDS_PER_KILOGRAM = 2.2;  // Create constant

System.out.println("Kilograms      Pounds");

// Display table
for (int i = 1; i <= 199; i += 2) {
System.out.printf(
"%-15d%6.1f\n", i, (i * POUNDS_PER_KILOGRAM));
}
}
}

## (将英里转換成千米）编写程序，显示下面的表格（注意：1 英里为1.609 千米）。

/*
(Conversion from miles to kilometers) Write a program that displays the following
table (note that 1 mile is 1.609 kilometers):
Miles           Kilometers
1               1.609
2               3.218
...
9               14.481
10              16.090
*/
public class Exercise_05_03 {
public static void main(String[] args) {
// Create a constant number of kilometers in a mile
final double KILOMETERS_PER_MILE = 1.609;

System.out.println(
"Miles        Kilometers");

// Create and display table showing conversion from miles to kilometers
for (int i = 1; i <= 10; i++) {
System.out.printf(
"%-13d%-10.3f\n", i, (i * KILOMETERS_PER_MILE));
}
}
}

## (千克与磅之间的互换）编写一个程序，并排显示下列两个表格。

public class Exercise_05_04 {

public static void main(String[] args) {
// Create constant value for number of pounds per kilogram
final double POUNDS_PER_KILOGRAM = 2.2;

System.out.println(
"Kilograms    Pounds     |     Pounds      Kilograms");
for (int k = 1, p = 20; k <= 199 && p <= 515; k += 2, p += 5) {
System.out.printf(
"%-12d%7.1f", k, (k * POUNDS_PER_KILOGRAM));
System.out.print("     |     ");
System.out.printf(
"%-9d%12.2f\n",
p, (p / POUNDS_PER_KILOGRAM));
}
}
}

## (财务应用程序：计算将来的学费）

/*
(Financial application: compute future tuition) Suppose that the tuition for a university
is $10,000 this year and increases 5% every year. In one year, the tuition will be$10,500. Write a program that computes the tuition in ten years and the
total cost of four years’ worth of tuition after the tenth year.
*/
public class Exercise_05_07 {
public static void main(String[] args) {
int totalCost = 0;		// Accumulate total cost of four years tution
int tuition = 10000;
int tuitionTenthYear;

for (int year = 1; year <= 14; year++) {
// Increase tution by 5% every year
tuition += (tuition * 0.05);

if (year > 10) // Test for after 10 years
totalCost += tuition; // Accumulate tution cost

// Cost of tution in ten years
if (year == 10)
tuitionTenthYear = tuition;
}

// Display the cost of tution in ten years
System.out.println("Tuition in ten years: $" + tuitionTenthYear); // Display the cost of four years' worth of tution after tenth year System.out.println("Total cost for four years' worth of tuition" + " after the tenth year:$" + totalCost);
}
}

## (找出最高分）

import java.util.Scanner;

public class Exercise_05_05 {

public static void main(String[] args) {
// Create Scanner object
Scanner input = new Scanner(System.in);

int highestScore = 0;      // Holds the hightest student score
String highestScoreName = ""; // Holds the student name with highest score

// Prompt the user to enter the number of students
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();

// Prompt the user to enter each student's name and score
System.out.println("Enter each student’s name and score");
for (int i = 0; i < numberOfStudents; i++) {
System.out.print(
"Student: " + (i + 1) +
"\n   Name: ");
String name = input.next();
System.out.print(
"   Score: ");
int score = input.nextInt();

// Test if score is higher than highest score
if (score > highestScore) {
highestScore = score;
highestScoreName = name;
}

}

// Display the name of the student with the highest score
System.out.println("Student with the highest score: " + highestScoreName);
}
}

## (找出两个分教最高的学生）

import java.util.Scanner;

public class Exercise_05_06 {

public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);

// Prompt the user to enter the number of students
System.out.print("Enter the number of students: ");
int numberOfStudents = input.nextInt();

int score,          // Holds students' score
highest = 0,      // Highest score
secondHigest = 0;  // Second highest score
String name = "",    // Holds students' name
student1 = "",  // Highest scoring student name
student2 = "";  // Second highest scoring student name

// Prompt the user to enter each students' name and score
System.out.println("Enter each students' name and score:");
for (int i = 0; i < numberOfStudents; i++) {
System.out.print(
"Student: " + (i + 1) + "\n   Name: ");
name = input.next();
System.out.print("   Score: ");
score = input.nextInt();

if (i == 0) {
// Make the first student the highest scoring student so far
highest = score;
student1 = name;
} else if (i == 1 && score > highest) {
// Second student entered scored
// higher than first student
secondHigest = highest;
highest = score;
student2 = student1;
student1 = name;
} else if (i == 1) {
// Second student entered scored
// lower than first student
secondHigest = score;
student2 = name;
} else if (i > 1 && score > highest && score > secondHigest) {
// Last student entered has the highest score
secondHigest = highest;
student2 = student1;
highest = score;
student1 = name;
} else if (i > 1 && score > secondHigest) {
// Last student entered has the second highest score
student2 = name;
secondHigest = score;
}
}

// Display the student with the hightest score
// and the student with the second-hightest score.
System.out.println(
"Higest scoring student: " + student1 +
"\nSecond Higest scoring student: " + student2);
}
}

## (找出能被5 和6 整除的數）

public class Exercise_05_07 {

public static void main(String[] args) {
final int NUMBERS_PER_LINE = 10;  // Display 10 numbers per line
int count = 0;  // Count the number of numbers divisible by 5 and 6

// Test all numbers from 100 to 1,000
for (int i = 100; i <= 1000; i++) {
// Test if number is divisible by 5 and 6
if (i % 5 == 0 && i % 6 == 0) {
count++;  // increment count
// Test if numbers per line is 10
if (count % NUMBERS_PER_LINE == 0) {
System.out.println(i);
} else {
System.out.print(i + " ");
}
}
}
}
}

## (找出能被5 或6 整除，但不能被两者同时整除的数）

public class Exercise_05_08 {

public static void main(String[] args) {
final int NUMBERS_PER_LINE = 10;  // Number of numbers in each line displayed
int count = 0; // Count the number divisible by 5 or 6, but not both

for (int i = 100; i <= 200; i++) {
if (i % 5 == 0 ^ i % 6 == 0) {
count++;
if (count % NUMBERS_PER_LINE == 0) {
System.out.println(i);
} else {
System.out.print(i + " ");
}
}
}
System.out.println();
}
}

## (求满足${ n }^{ 2 }$>12 000 的n 的最小值）使用while 循环找出满足n 大于12 000 的最小整数n

public class Exercise_05_09 {

public static void main(String[] args) {
int n = 0;  // Start n at 0

// Find the smallest n such that n^2 > 12,000
while (Math.pow(n, 2) < 12000) {
n++;    // Increment n
}

// Display result
System.out.println(
"The smallest integer n such that n^2 is greater than 12,000: " + n);
}
}

## (求满足${ n }^{ 3}$<12 000 的n 的最大值）用while 循环找出满足n3 小于12 000 的最大整数n。

public class Exercise_05_10 {

public static void main(String[] args) {
int n = 0;  // Intialize n at 0;

// Find the largest n such that n^3 is < 12,000
while (Math.pow(n + 1, 3) < 12000) {
n++;    // Increment n
}

// Display result
System.out.println(
"Largest integer n such that n^3 is less than 12,000: " + n);
}
}

## (显示ACSII 码字符表）

public class Exercise_05_11 {

public static void main(String[] args) {
// Number of characters per line
final int NUMBER_OF_CHARACTERS_PER_LINE = 10;
int count = 0;  // Count the number of characters

// Print the ASCII characters from ! to ~
for (int i = 33; i <= 126; i++) {
count++;  // Increment count
// Display 10 characters per line
if (count % 10 == 0) {
System.out.println((char) i);
} else {
System.out.print((char) i + " ");
}
}
System.out.println();
}
}

## (找出一个整数的因子）

import java.util.Scanner;

public class Exercise_05_12 {

public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);

// Prompt the user to enter an integer
System.out.print("Enter an integer: ");
int number = input.nextInt();
int index = 2; // Numbers to test as factors

// Find and display all the smallest factors in increasing order
while (number / index != 1) {
// Test as a factor of number
if (number % index == 0) {
System.out.print(index + ", ");
number /= index;
} else {
index++; // Increment index
}
}
System.out.println(number + ".");
}
}

## (显示金字塔）

import java.util.Scanner;

public class Exercise_05_13 {

public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter an integer from 1 to 15
System.out.print("Enter the number of lines: ");
int numberOfLines = input.nextInt();

// Display pyramid
for (int rows = 1; rows <= numberOfLines; rows++) {
// Create spaces in each row
for (int s = numberOfLines - rows; s >= 1; s--) {
System.out.print("  ");
}
// Create decending numbers in each row
for (int l = rows; l >= 2; l--) {
System.out.print(l + " ");
}
// Create ascending number in each row
for (int r = 1; r <= rows; r++) {
System.out.print(r + " ");
}
// End line
System.out.println();
}
}
}

## (打印金字塔形的教字）

public class Exercise_05_14 {

public static void main(String[] args) {
int startRight = 0,  // Initialize decending numbers
endSpace = 7;    // Initialize number of white space in row
// Display number of rows and numbers in each row
for (int row = 1; row <= 128; row += row) {
// Display white space
for (int startSpace = 0; startSpace < endSpace; startSpace++) {
System.out.print("    ");
}
// Display acending numbers
for (int l = 1; l <= row; l += l) {
System.out.printf("%4d", (l));
}
// Display decending numbers
for (int r = startRight; r > 0; r /= 2) {
System.out.printf("%4d", (r));
}
System.out.println();  // End line
endSpace--;        // Decrement endSpace
startRight = row;      // Assign row to startRight
}
}
}

## (财务应用程序：比较不同利率下的贷款）

import java.util.Scanner;

public class Exercise_05_15 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

// Prompt the user to enter the loan amount and
// loan period in number of years
System.out.print("Loan Amount: ");
double loanAmount = input.nextDouble();
System.out.print("Number of Years: ");
int numberOfYears = input.nextInt();

System.out.println(
"Interest Rate    Monthly Payment    Total Payment");

// Display table with interest rates
for (double i = 5.0; i <= 8; i += 0.125) {
System.out.printf("%-5.3f", i);
System.out.print("%           ");
double monthlyInterestRate = i / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate / (1
- 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
System.out.printf("%-19.2f", monthlyPayment);
System.out.printf("%-8.2f\n", (monthlyPayment * 12) * numberOfYears);
}
}
}

## ( 示例抵消错误）

$1+\cfrac { 1 }{ 2 } +\frac { 1 }{ 3 } +…+\frac { 1 }{ n }$

public class Exercise_05_16 {

public static void main(String[] args) {
// Compute series from left to right
double sumLeftToRight = 0.0;
for (double i = 1.0; i <= 50000.0; i++) {
sumLeftToRight += 1 / i;
}

// Display result of series sum from left to right
System.out.println("Summation of series left to right: " + sumLeftToRight);

// Compute series from right to left
double sumRightToLeft = 0.0;
for (double i = 50000.0; i >= 1.0; i--) {
sumRightToLeft += 1 / i;
}

// Display result of series sum from right to left
System.out.println("Summation of series right to left: " + sumRightToLeft);

// Compare the results
System.out.println("Summation of the series right to left - "
+ "Summation of the series left to right: "
+ (sumRightToLeft - sumLeftToRight));
}
}

## (数列求和）编写程序，计算下面数列的和：

$1+\cfrac { 3 }{ 5 } +\frac { 5 }{ 7 } +\frac { 7 }{ 9 } +\frac { 9 }{ 11 } …+\frac { 97 }{ 99 }$
public class Exercise_05_17 {

public static void main(String[] args) {
// Sum the series
double sum = 0.0;
for (double n = 1.0; n <= 97.0; n += 2) {
sum += n / (n + 2);
}

System.out.println(
"Series: 1 / 3 + 3 / 5 + 5 / 7 + 7 / 9 + 9 / 11 + 11 / 13 + " +
" ... + 95 / 97 + 97 / 99");
System.out.println("Sum of series: " + sum);
}
}

## (计算π）

public class Exercise_05_18 {

public static void main(String[] args) {
// Compute PI value for i = 10000,
double sum = 0;
double value = 10000.0;
for (double d = 1; d <= (2 * value - 1); d += 2) {
sum += 1 / d;
d += 2;
sum -= 1 / d;
}
double pi = 4 * sum;

// Display result
System.out.println("PI value for i = 10000: " + pi);

// Compute PI value for i = 20000,
sum = 0;
value = 20000.0;
for (double d = 1; d <= (2 * value - 1); d += 2) {
sum += 1 / d;
d += 2;
sum -= 1 / d;
}
pi = 4 * sum;

// Display result
System.out.println("PI value for i = 20000: " + pi);

// Compute PI value for i = 20000,
sum = 0;
value = 100000.0;
for (double d = 1; d <= (2 * value - 1); d += 2) {
sum += 1 / d;
d += 2;
sum -= 1 / d;
}
pi = 4 * sum;

// Display result
System.out.println("PI value for i = 100000: " + pi);
}
}