1.编写一个程序,把变量n的初始值设置为1678,然后利用除法运算和取余运算把变量的每位数字都提出来并打印,输出结果为:n=1678n的每位数字是1,6,7,8。
public static void main(String[]args) {
int n=1678;
int a,b,c,d;
a=n%10;
b=n/10%10;
c=n/100%10;
d=n/1000;
System.out.print(d+" ");
System.out.print(c+" ");
System.out.print(b+" ");
System.out.print(a+" ");
}
}
输出结果:
2.编写Java程序,接受用户输入的1~12之间的整数,若不符合条件则重新输入,利用switch语句输出对应月份的天数。
public static void main(String[] args) {
int a = 0;
Boolean flag = true;
System.out.println("输入月份弹出天数:");
Scanner scanner = new Scanner(System.in);
a = scanner.nextInt();
if ((a < 1) || (a > 12)) {
flag = false;
}
while (flag == false) {
System.out.println("输错了再来:");
a = scanner.nextInt();
if ((a <= 12) && (a >= 1)) {
flag = true;
}
}
switch (a) {
case 1:
System.out.println("31");
break;
case 2:
System.out.println("28");
break;
case 3:
System.out.println("31");
break;
case 4:
System.out.println("30");
break;
case 5:
System.out.println("31");
break;
case 6:
System.out.println("30");
break;
case 7:
System.out.println("31");
break;
case 8:
System.out.println("31");
break;
case 9:
System.out.println("30");
break;
case 10:
System.out.println("31");
break;
case 11:
System.out.println("30");
break;
case 12:
System.out.println("31");
break;
}
}
}
输出结果:
3.编写一个方法来计算10000以内的素数之和并输出。
public static void main(String[] args) {
int b, d = 0;
for (b = 2; b < 10000; b++) {
Boolean flag = true;
for (int i = 2; i < b; i++) {
if (b % i == 0) {
flag = false;
break;
}
}
if (flag == true) {
d = d + b;
}
}
System.out.println("总和为" + d);
}
}
输出结果:
4.编写Java程序实现:输入一组整数存放在数组中,比较并输出其中的最大值和最小值;再将数组元素从小到大排序并输出。
import java.util.Arrays;
import java.util.Scanner;
public class fhkjs {
public static void main(String[] args) {
int agr[] = new int[5];
Scanner scanner = new Scanner(System.in);
System.out.println("输入五个数字:");
for (int i = 0; i < agr.length; i++) {
agr[i] = scanner.nextInt();
}
int max = agr[0], min = agr[0];
for (int a = 1; a < agr.length; a++) {
if (max < agr[1]) {
max = agr[1];
}
if (min > agr[1]) {
min = agr[1];
}
}
System.out.println("max=" + max + " min=" + min);
Arrays.sort(agr);
for (int i : agr) {
System.out.println(i + "");
}
}
}
输出结果:
5.使用数组存储一个英文句子“Java is an object oriented programming language”。显示该句子,并计算出每个单词的平均字母数。
public static void main(String[] args) {
String str="java is an object oriented programming language";
String[] split=str.split(" ");
for (int i = 0; i < split.length; i++) {
System.out.print(split[i]);
System.out.print(" ");
}
System.out.println();
double res=0;
for (int i = 0; i < split.length; i++) {
res+=split[i].length()*1.0/ split.length;
}
System.out.println("平均字符长度为:" + res);
}
}