用java的多态写一个将输入数据按特定要求原样输出的代码并且第一行是整数t,下面的每行以一个字母开头,然后跟着一个整数,两者用空格分隔,字母只会是A或B
时间: 2023-05-19 16:01:51 浏览: 121
以下是用 Java 多态实现的将输入数据按特定要求原样输出的代码:
```
import java.util.Scanner;
abstract class Data {
protected char letter;
protected int number;
public Data(char letter, int number) {
this.letter = letter;
this.number = number;
}
public abstract void print();
}
class AData extends Data {
public AData(char letter, int number) {
super(letter, number);
}
public void print() {
System.out.println(letter + " " + number);
}
}
class BData extends Data {
public BData(char letter, int number) {
super(letter, number);
}
public void print() {
System.out.println(number + " " + letter);
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
Data[] data = new Data[t];
for (int i = 0; i < t; i++) {
char letter = scanner.next().charAt(0);
int number = scanner.nextInt();
if (letter == 'A') {
data[i] = new AData(letter, number);
} else {
data[i] = new BData(letter, number);
}
}
for (int i = 0; i < t; i++) {
data[i].print();
}
}
}
```
第二个问题:lua closure factory 完整代码
以下是 Lua 闭包工厂的完整代码:
```
function make_adder(x)
return function(y)
return x + y
end
end
add5 = make_adder(5)
print(add5(3)) -- 输出 8
```
第三个问题:中文加密
中文加密可以使用简单的替换密码来实现。例如,将每个中文字符替换为另一个中文字符,可以使用以下代码:
```
function encrypt(str)
local result = ""
for i = 1, #str do
local c = str:sub(i, i)
if c >= "一" and c <= "龥" then -- 判断是否为中文字符
result = result .. string.char(math.random(0x4e00, 0x9fa5)) -- 替换为随机中文字符
else
result = result .. c -- 其它字符不加密
end
end
return result
end
function decrypt(str)
local result = ""
for i = 1, #str do
local c = str:sub(i, i)
if c >= "一" and c <= "龥" then -- 判断是否为中文字符
result = result .. string.char(math.random(0x4e00, 0x9fa5)) -- 解密为随机中文字符
else
result = result .. c -- 其它字符不解密
end
end
return result
end
local str = "这是一段中文文本"
local encrypted = encrypt(str)
print(encrypted)
local decrypted = decrypt(encrypted)
print(decrypted)
```
阅读全文