9.11
int X = 100; int Y = 200; System.out.println("X+Y=" + X + Y); System.out.println(X + Y + "=X+Y");
代码运行结果是
X+Y=100200
300=X+Y
字符串表示文本,数字表示类型
当一个字符串与一个数字相加时,Java会自动将数字转换为字符串,然后进行拼接。
生成三十个四则运算题目
package project; import java.util.Random; public class ArithmeticGenerator { public static void main(String[] args) { int num=30; for (int i = 1; i <= num; i++) { String question = generateQuestion();//generateQuestion()函数后面用到 System.out.println( question); } } public static String generateQuestion() { Random random = new Random(); // 随机生成两个操作数和一个运算符 int operand1 = random.nextInt(100) + 1; // 生成1-100之间的随机整数 int operand2 = random.nextInt(100) + 1;//还是生成随机数 char operator = getRandomOperator(); // 构建题目字符串 String question = operand1 + " " + operator + " " + operand2 + " = "; return question; } // 随机生成一个运算符 public static char getRandomOperator() { char[] operators = {'+', '-', '*', '/'}; Random random = new Random(); int index = random.nextInt(operators.length); return operators[index]; } }