Java 基础题
使用嵌套的for循环打印九九乘法表。
public class Multiplication {
public static void main(String[] args) {
for (int i = 1;i<=9;i++){
for(int j = 1;j<=i;j++){
System.out.print(j+"*"+i+"="+i*j+" ");
}
System.out.println();
}
}
}
使用嵌套的for循环打印直角三角形。
package com.alan.demo01;
public class test01 {
public static void main(String[] args) {
print(7);
}
public static void print(int n) {
for (int i = 1; i <= n; i++) {
for (int i1 = 1; i1 <= i; i1++) {
System.out.print("*");
}
System.out.println();
}
}
}
使用数组与循环判断语句打印数组中的奇数与偶数
public static void main(String[] args) {
int[] array = {6, 66, 43, 45, 38, 64, 21, 99, 88};
int sum = 0;
int sum01 = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
sum += array[i];
} else {
sum01 += array[i];
}
}
System.out.println("偶数和" + sum);
System.out.println("奇数和" + sum01);
}
使用random 、scanner、循环、判断语句制作猜数字小游戏
package cn.ework;
import java.util.Random;
import java.util.Scanner;
public class test07 {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
while (true) {
int player = scanner.nextInt();
int computer = random.nextInt(3);
if ((computer == 0 && player == 0) || (computer == 1 && player == 1) || (computer == 2 && player == 2)) {
System.out.println("平局");
break;
} else if ((computer == 0 && player == 1) || (computer == 2 && player == 0) || (computer == 1 && player == 2)) {
System.out.println("你输了");
break;
} else if ((computer == 0 && player == 2) || (computer == 2 && player == 1) || (computer == 1 && player == 0)) {
System.out.println("你赢了");
break;
} else {
System.out.println("错误");
}
}
}
}
使用while循环、判断语句、scanner、random语句制作电脑猜拳游戏
package cn.ework;
import java.util.Random;
import java.util.Scanner;
public class test07 {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
while (true) {
int player = scanner.nextInt();
int computer = random.nextInt(3);
if ((computer == 0 && player == 0) || (computer == 1 && player == 1) || (computer == 2 && player == 2)) {
System.out.println("平局");
break;
} else if ((computer == 0 && player == 1) || (computer == 2 && player == 0) || (computer == 1 && player == 2)) {
System.out.println("你输了");
break;
} else if ((computer == 0 && player == 2) || (computer == 2 && player == 1) || (computer == 1 && player == 0)) {
System.out.println("你赢了");
break;
} else {
System.out.println("错误");
}
}
}
}
|
|