各位这道完全看不懂,请讲解大恩大德无以回报祝你买菜打折喝奶茶半价
SuperClass的代码没有吗?
少了很多代码,代码不全。
在这个世界不可能存在完美的东西,不管完美的思维有多么缜密,细心,我们都不可能考虑所有的因素,这就是所谓的智者千虑必有一失。同样的道理,计算机的世界也是不完美的,异常情况随时都会发生,我们所需要做的就是避免那些能够避免的异常,处理那些不能避免的异常。这里我将记录如何利用异常还程序一个“完美世界”。
异常处理最根本的优势就是将检测错误(由被调用的方法完成)从处理错误(由调用方法完成)中分离出来。(也就是没有那么多if语句了)
编写Java程序,从键盘读取用户输入两个字符串并重载:
代码实现:
import java.util.Scanner;
public class StringOverload {
// 重载方法1:连接两个字符串
public static String concat(String str1, String str2) {
return str1 + str2;
}
// 重载方法2:交换两个字符串的位置
public static void swap(String[] strs) {
String temp = strs[0];
strs[0] = strs[1];
strs[1] = temp;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.next();
String str2 = input.next();
System.out.println(concat(str1, str2));
swap(new String[]{str1, str2});
System.out.println(str1 + " " + str2);
}
}
计算分数序列:2/1,3/2,5/3,8/5,13/8,21/13…求出这个数列的前20项之和:
代码实现:
public class FractionSequence {
// 计算前n项的和
public static double getSum(int n) {
int x = 2, y = 1;
double sum = 0;
for (int i = 0; i < n; i++) {
sum = sum + (double) x / y;
x = x ^ y;
y = x ^ y;
x = x ^ y;
x = x + y;
}
return sum;
}
public static void main(String[] args) {
System.out.println("前二十项相加之和为:" + getSum(20));
}
}
Java模拟登录逻辑。判断用户输入的账号,密码与注册时的是否一致,以及判断用户输入的验证码是否正确:
代码实现:
import java.util.Random;
import java.util.Scanner;
public class Login {
// 注册账号和密码
public static String account = "abc123";
public static String password = "a123";
// 验证码生成方法
public static String generateVerificationCode() {
String str1 = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
String str2 = "abcdefghijklmnopqrstuvwxyz";
String str3 = "0123456789";
String str = str1 + str2 + str3;
int length = str.length();
Random random = new Random();
char[] verificationCode = new char[4];
for (int i = 0; i < verificationCode.length; i++) {
verificationCode[i] = str.charAt(random.nextInt(length));
}
return new String(verificationCode);
}
public static void main(String[] args) {
// 产生验证码并输出
String verificationCode = generateVerificationCode();
System.out.println("验证码为:" + verificationCode);
// 输入账号、密码和验证码
Scanner input = new Scanner(System.in);
System.out.println("请输入用户名:");
String inAccount = input.next();
System.out.println("请输入密码:");
String inPassword = input.next();
System.out.println("请输入验证码:");
String inVerificationCode = input.next();
// 判断账号密码是否一致
boolean same1 = inAccount.equals(account) && inPassword.equals(password);
// 判断验证码是否正确(不区分大小写)
boolean same2 = inVerificationCode.equalsIgnoreCase(verificationCode);
// 输出结果
String loadSuccess = same1 && same2 ? "登录成功" : "账号密码或验证码错误";
System.out.println(loadSuccess);
}
}