一、动态字符串
将一个由英文字母组成的字符串转换成从末尾开始每三个字母用逗号分隔的形式。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
StringBuilder stringBuilder = new StringBuilder();
int n = str.length()%3;
for (int i = 0; i < n; i++) {
char ch = str.charAt(i);
stringBuilder.append(ch);
}
stringBuilder.append(",");
int count = 0;
for (int i = n; i < str.length(); i++) {
char ch = str.charAt(i);
count++;
if(count % 3 == 0 && i != str.length() - 1) {
stringBuilder.append(ch).append(",");
}else {
stringBuilder.append(ch);
}
}
System.out.println(stringBuilder.toString());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
二、十进制数转二进制数
控制台随机输入一个十进制数,请你将它转换为二进制数并输出
1.直接使用包装类方法
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(Integer.toBinaryString(n));
}
}
1
2
3
4
5
6
7
2.暴力求法
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if(n == 0) {
System.out.println(n);
return;
}
StringBuilder str = new StringBuilder();
while(n > 0) {
str.append(n % 2);
n /= 2;
}
System.out.println(str.reverse());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
三、判断学生成绩
定义一个方法用于录入学生的考试成绩,要求考试成绩必须在0-100之间,不满足就产生一个自定义异常,控制台输出一个错误信息"分数不合法"(请输出自定义异常对象的错误信息,将错误信息设置为分数不合法)
import java.util.*;
public class Main {
public static void main(String[] args) throws ScoreException{
Scanner scanner = new Scanner(System.in);
int score = scanner.nextInt();
try {
if(score < 0 || score > 100) {
throw new ScoreException("分数不合法");
}else {
System.out.println(score);
}
} catch(ScoreException e) {
System.out.println(e.getMessage());
}
}
}
class ScoreException extends Exception {
public ScoreException(String message) {
super(message);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
四、统计字符串中字母出现次数
给定一个字符串,随机输入一个字母,判断该字母在这个字符串中出现的次数
public class Main {
public static void main(String[] args) {
String string = "H e l l o ! n o w c o d e r";
Scanner scanner= new Scanner(System.in);
String word = scanner.next();
scanner.close();
System.out.println(check(string, word));
}
public static int check(String str, String word) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(ch == word.charAt(0)) {
count++;
}
}
return count;
}
}