验证与 getter
Coddy 面向 C 开发者的 Java 课程的第 36 课,共 48 课。
C 通常会将结构体定义隐藏在不透明的公共声明之后,并提供带验证功能的函数。可见结构体中的字段不会受到 private 关键字的保护。Java 的私有字段和公共方法可以直接表示这种边界。写入前先进行验证,这样拒绝操作时现有状态就能保持不变;公共字段不会自动调用 setter。
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>
struct Meter {int level;};
static bool set_level(struct Meter *meter,int value) { if(value<0) return false; meter->level=value; return true; }
int main(void) {
struct Meter m={4}; bool accepted=set_level(&m,-1); printf("%s %d\n",accepted?"true":"false",m.level);
return 0;
}
Java
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
static class Meter {private int level=4;int getLevel(){return level;}void setLevel(int n){if(n<0)throw new IllegalArgumentException();level=n;}}
public static void main(String[] args) {
Meter m=new Meter();try{m.setLevel(-1);}catch(IllegalArgumentException e){}System.out.println(m.getLevel());
}
}
这些示例分别展示语言行为,使用的值可能不同。请分别跟踪每个示例,不要假设它们的预期输出相同。Java 任务会通过可编辑的类,将相同概念应用于新的输入。
挑战
简单输入依次为非负的初始等级和任意整数更新值。Meter(int) 和 setLevel(int) 遇到负数时,会在修改状态前抛出 IllegalArgumentException。提供 getLevel() 和 toString(),格式为 level=N。返回 accepted 或 rejected,然后返回仪表文本。
通过 Exercise.solve(List<String> input) 返回准确的结果文本,不要在末尾添加换行符。可见的锁定文件 Main.java 会读取所有输入行,并在打印返回的文本时添加一个末尾换行符。不要在可编辑的方法中打印内容。除非另有说明,所有整数和算术结果都能用 Java int 表示。
可编辑的文件:Meter.java、Exercise.java、Text.java。Text.java 提供可重复使用的解析和格式化辅助方法。所有文件都位于未命名包中,并会一起编译。Main.java 是唯一的入口点,不能编辑。
可见的锁定驱动程序还会在运行输入用例前,对独立的新对象调用所需的类 API。请实现这些 API;仅硬编码最终输出是不够的。
亲手试试
import java.io.*;
import java.util.*;
public class Main {
private static void check(boolean condition) {
if (!condition) throw new AssertionError("Required public API behavior failed");
}
public static void main(String[] args) throws Exception {
List<String> input = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = reader.readLine()) != null) input.add(line);
Meter m=new Meter(4);boolean bad=false;try{m.setLevel(-1);}catch(IllegalArgumentException e){bad=true;}check(bad&&m.getLevel()==4);bad=false;try{new Meter(-3);}catch(IllegalArgumentException e){bad=true;}check(bad);m.setLevel(7);check(m.toString().equals("level=7"));
System.out.println(Exercise.solve(input));
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Java中的所有课
自己练习: Java 在线编译器