Java编程练习解答汇总
立即解锁
发布时间: 2025-08-17 02:35:41 阅读量: 18 订阅数: 22 


Java编程基础与SCJP认证指南
# Java编程练习解答汇总
## 1. Java编程基础
### 1.1 可打印字符栈
`PrintableCharStack` 类的 `printStackElements()` 方法用于打印栈中的元素,且不会弹出元素。以下是相关代码:
```java
//Filename: PrintableCharStack.java
public class PrintableCharStack extends CharStack {
// Instance method
public void printStackElements() {
for (int i = 0; i <= topOfStack; i++)
System.out.print(stackArray[i]); // print each char on terminal
System.out.println();
}
// Constructor calls the constructor of the superclass explicitly.
PrintableCharStack(int capacity) { super(capacity); }
}
//Filename: Client.java
public class Client {
public static void main(String[] args) {
// Create a printable character stack.
PrintableCharStack stack = new PrintableCharStack(40);
// Create a string to push on the stack:
String str = "!no tis ot nuf era skcatS";
int length = str.length();
// Push the string char by char onto the stack:
for (int i = 0; i < length; i++) {
stack.push(str.charAt(i));
}
System.out.print("Stack contents: ");
stack.printStackElements();
// Pop and print each char from the stack:
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
System.out.println();
System.out.print("Stack contents: ");
stack.printStackElements();
}
}
```
### 操作步骤
1. 创建 `PrintableCharStack` 对象。
2. 将字符串逐字符压入栈中。
3. 调用 `printStackElements()` 方法打印栈内容。
4. 弹出并打印栈中的每个字符。
5. 再次调用 `printStackElements()` 方法打印栈内容。
## 2. 语言基础
### 2.1 温度转换程序
以下程序可将华氏温度转换为摄氏温度,且编译和运行无错误:
```java
//Filename: Temperature.java
public class Temperature {
public static void main(String[] args) {
double fahrenheit = 62.5;
double celsius = f2c(fahrenheit);
System.out.println(fahrenheit + "F" + " = " + celsius + 'C');
}
static double f2c(double fahr) {
return (fahr - 32) * 5 / 9;
}
}
```
### 操作步骤
1. 定义华氏温度变量。
2. 调用 `f2c()` 方法将华氏温度转换为摄氏温度。
3. 打印转换结果。
## 3. 声明
### 3.1 编辑上下文的JavaBean
```java
public class EditContext {
private Object selected;
public void setSelected(Object newSelected) {
selected = newSelected;
}
public Object getSelected() {
return selected;
}
}
```
### 3.2 测验评分程序
```java
public class QuizGrader {
enum Result { CORRECT, WRONG, UNANSWERED }
public static final int PASS_MARK = 5;
public static void main(String[] args) {
String[] correctAnswers = { "C", "A", "B", "D", "B", "C", "C", "A" };
System.out.println("Question Submitted Ans. Correct Ans. Result");
int numOfCorrectAnswers = 0;
int numOfWrongAnswers = 0;
int numOfUnanswered = 0;
for (int i = 0; i < args.length; i++) {
String submittedAnswer = args[i];
String correctAnswer = correctAnswers[i];
Result result = determineResult(submittedAnswer, correctAnswer);
System.out.printf("%5d%10s%15s%15s%n",
i + 1, submittedAnswer, correctAnswer, result);
switch (result) {
case CORRECT:
numOfCorrectAnswers++;
break;
case WRONG:
numOfWrongAnswers++;
break;
case UNANSWERED:
numOfUnanswered++;
break;
}
}
System.out.println("No. of correct answers: " + numOfCorrectAnswers);
System.out.println("No. of wrong answers: " + numOfWrongAnswers);
System.out.println("No. of questions unanswered: " + numOfUnanswered);
System.out.println("The candidate " +
(numOfCorrectAnswers >= PASS_MARK ? "PASSED." : "FAILED."));
}
public static Result determineResult(String submittedAnswer,
String correctAnswer) {
Result result = null;
if (submittedAnswer.equals(correctAnswer))
result = Result.CORRECT;
else if (submittedAnswer.equals("X"))
result = Result.UNANSWERED;
else
result = Result.WRONG;
return result;
}
}
```
### 操作步骤
1. 定义正确答案数组。
2. 遍历提交的答案,调用 `determineResult()` 方法判断结果。
3. 统计正确、错误和未回答的问题数量。
4. 根据正确答案数量判断考生是否通过。
## 4. 访问控制
### 4.1 账户和数据库类
```java
//Filename: Account.java
package com.megabankcorp.records;
public class Account { }
//Filename: Database.java
package com.megabankcorp.system;
import com.megabankcorp.records.Account;
public abstract class Database {
public abstract void deposit(Account acc, double amount);
public abstract void withdraw(Account acc, double amount);
protected abstract double amount(Account acc);
final void transfer(Account from, Account to, double amount) {
withdraw(from, amount);
deposit(to, amount);
}
}
```
### 操作说明
- `deposit()` 和 `withdraw()` 方法为抽象方法,可在任何地方访问。
- `amount()` 方法为抽象方法,仅在包内和子类中可访问。
- `transfer()` 方法为最终方法,仅在包内可访问。
## 5. 运算符和表达式
### 5.1 阳光传播时间计算
```java
//Filename: Sunlight.java
public class Sunlight {
public static void main(String[] args) {
int kmFromSun = 150000000;
int lightSpeed = 299792458;
long mFromSun = kmFromSun * 1000L;
int seconds = (int) (mFromSun / lightSpeed);
System.out.print("Light will use ");
printTime(seconds);
System.out.println(" to travel from the sun to the earth.");
}
public static void printTime(int sec) {
int min = sec / 60;
sec = sec - (min * 60);
System.out.print(min + " minute(s) and " + sec + " second(s)");
}
}
```
### 操作步骤
1. 定义地球到太阳的距离和光速。
2. 将距离转换为米,使用 `long` 类型避免溢出。
3. 计算光从太阳传播到地球所需的时间。
4. 调用 `printTime()` 方法格式化输出时间。
## 6. 控制流
### 6.1 寻找质数
#### 使用 `for` 循环
```java
//Filename: ForPrimes.java
public class ForPrimes {
final static int MAX = 100;
public static void main(String[] args) {
numbers:
for (int num = 1; num < MAX; num++) {
int divLim = (int) Math.sqrt(num);
for (int div = 2; div <= divLim; div++)
if ((num % div) == 0) continue numbers;
System.out.println(num);
}
}
}
```
#### 使用 `while` 循环
```java
//Filename: WhilePrimes.java
public class WhilePrimes {
final static int MAX = 100;
public static void main(String[] args) {
int num = 1;
numbers:
while (num < MAX) {
int number = num++;
int divLim = (int) Math.sqrt(number);
int div = 2;
while (div <= divLim)
if ((number % div++) == 0) continue numbers;
System.out.println(number);
}
}
}
```
### 操作步骤
1. 设定最大范围。
2. 遍历范围内的每个数。
3. 对于每个数,检查是否能被小于其平方根的数整除。
4. 若不能整除,则该数为质数,打印输出。
### 6.2 发电厂控制系统
```java
package energy;
public class PowerPlant {
Reactor core;
PowerPlant() {
core = new Reactor();
}
public void soundEvacuateAlarm() {
}
public int getOptimalThroughput() {
return 0;
}
public static void main(String[] args) {
PowerPlant plant = new PowerPlant();
Control ctrl = new Control(plant);
ctrl.runSystem();
}
}
class Reactor {
public int getThroughput() {
return 0;
}
public boolean isCritical() {
return false;
}
void increaseThroughput() throws ReactorCritical {
}
void decreaseThroughput() {
}
}
class ReactorCritical extends Exception {}
class Control {
PowerPlant thePlant;
final static int TOLERANCE = 10;
public Control(PowerPlant p) {
thePlant = p;
}
public void runSystem() {
try {
while (true) {
int optimalThroughput = thePlant.getOptimalThroughput();
if (needAdjustment(optimalThroughput))
adjustThroughput(optimalThroughput);
}
} catch (ReactorCritical rc) {
thePlant.soundEvacuateAlarm();
} finally {
shutdown();
}
}
public boolean needAdjustment(int target) throws ReactorCritical {
if (thePlant.core.isCritical())
throw new ReactorCritical();
return Math.abs(thePlant.core.getThroughput() - target) > TOLERANCE;
}
public void adjustThroughput(int target) throws ReactorCritical {
while (needAdjustment(target)) {
if ((thePlant.core.getThroughput() - target) > TOLERANCE)
thePlant.core.increaseThroughput();
else
thePlant.core.decreaseThroughput();
}
}
public void shutdown() {
while (thePlant.core.getThroughput() > 0) {
thePlant.core.decreaseThroughput();
}
}
}
```
### 操作步骤
1. 创建 `PowerPlant` 对象和 `Control` 对象。
2. 调用 `Control` 对象的 `runSystem()` 方法。
3. 在 `runSystem()` 方法中,不断监测反应堆的最佳吞吐量和实际吞吐量。
4. 若两者差值超过容差,则调用 `adjustThroughput()` 方法调整吞吐量。
5. 若反应堆状态危急,触发疏散警报并关闭反应堆。
## 7. 面向对象编程
### 7.1 对数组应用函数
```java
//Filename: Exercise1.java
package chap07_PE1;
interface Function {
public int evaluate(int arg);
}
class Half implements Function {
public int evaluate(int arg) {
return arg / 2;
}
}
public class Exercise1 {
public static int[] applyFunctionToArray(int[] arrIn) {
int length = arrIn.length;
int[] arrOut = new int[length];
Function func = new Half();
for (int i = 0; i < length; i++)
arrOut[i] = func.evaluate(arrIn[i]);
return arrOut;
}
public static void main(String[] args) {
int length = 10;
int[] myArr = new int[length];
for (int i = 0; i < length;) myArr[i] = ++i;
for (int value : myArr) System.out.println(value);
myArr = applyFunctionToArray(myArr);
for (int value : myArr) System.out.print
```
0
0
复制全文
相关推荐









