Provide Best Programming Tutorials

编程作业 — Java循环

编写一个程序,随机产生一个0到100 之间且包含0 和100 的整数。程序提示用户连续输人一个数字,直到它和计算机随机产生的数字相匹配为止。对用户每次输入的数字,程序都要告诉用户该输入值是偏大了,还是偏小了,这样用户可以明智地进行下一轮的猜测。

下面是一个运行示例:

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
      System.out.print("\nEnter your guess: ");
      guess = input.nextInt();

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

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

编写程序,读入未指定个数的整数,判断读人的正数有多少个,读入的负数有多少个,然后计算这些输人值的总和及其平均值(不对 0 计数)。当输入为0 时,表明程序结束。将平均值以浮点数显示。下面是一个运行示例:

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

    // Display header for table
    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; 

		// Display table header
		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;

		// Display table header
		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));
		}
	}
}

(财务应用程序:计算将来的学费)

假设今年某大学的学费为10 000 美元,学费的年增长率为5%。— 年后,学费将是10 500 美元。编写程序,计算丨0 年后的学费.以及从现在开始的丨0 年后算起,4 年内总学费是多少?

/*
(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 整除的數)

编写程序,显示从100 到1000 之间所有能被5 和6 整除的数,每行显示10 个。数字之间用一个空格字符隔开。

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 整除,但不能被两者同时整除的数)

编写程序,显示从100 到200 之间所有能被5 或6 整除,但不能被两者同时整除的数,每行显示 10 个数。数字之间用一个空格字符隔开

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 码字符表)

编写一个程序,打印ASCII 字符表从到的字符。每行打印10 个字符。ASCII 码表如图所示。数字之间用一个空格字符隔开。

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();
  }
}

(找出一个整数的因子)

编写程序,读入一个整数,然后以升序显示它的所有最小因子。例如,若输人的整数是120, 那么输出就应该是:2, 2, 2, 3, 5。

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 + ".");
  }
}

(显示金字塔)

编写程序,提示用户输人一个在1到15 之间的整数,然后显示一个金字塔形状的图案,如下面的运行示例所示:

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();
    }
  }
}

(打印金字塔形的教字)

编写一个嵌套的for 循环,打印下面的输出

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
    }
  }
}

(财务应用程序:比较不同利率下的贷款)

编写程序,让用户输入贷款总额和以年为单位的贷款期限,然后显示利率从5% 到8%, 每次递增1/8 的过程中,每月的支付额和总支付额。下面是一个运行示例

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();

    // Display table header
    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);
    }
  }
}

( 示例抵消错误)

当处理一个很大的数字以及一个很小的数字的时候,会产生一个抵消错误( cancellation error)。例如,100 000 000.0 + 0.000 000 001 等于100 000 000.0。为了避免抵消错误,从而获得更加精确的结果,谨慎选择计算的次序。比如,在计算下面的数列时,从右到左计算要比从左到右计算得到的结果更精确:

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

编写程序对上面的数列从左到右和从右到左计算的结果进行比较,这里取n=50000。

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);
  }
}

(计算π)

使用下面的数列可以近似计算π:

编写程序. 显示当i=10000. 20000 100000 时 π 的值

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);
  }
}

Leave a Reply

Close Menu