java第三章代码练习
import java.util.*;
public class Example3_1 {
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
System.out.println("输入待移位的整数:");
int x=reader.nextInt();
System.out.println("输入移位量:");
int n=reader.nextInt();
System.out.println("左移位的结果:"+(x<<n));
System.out.println("右移位的结果:"+(x>>n));
}
}
public class Example3_2 {
public static void main(String args[]) {
char a[]={'金','木','水','火','土'};
char secret='z';
for(int i=0;i<a.length;i++) {
a[i]=(char)(a[i]^secret);
}
System.out.printf("密文: \n");
for(int i=0;i<a.length;i++){
System.out.printf("%3c",a[i]);
}
for(int i=0;i<a.length;i++)
a[i]=(char)(a[i]^secret);
System.out.printf("\n原文: \n");
for(int i=0;i<a.length;i++)
System.out.printf("%3c",a[i]);
}
}
import java.util.*;
public class Example3_3 {
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
double a=0,b=0,c=0;
System.out.print("输入边a:");
a=reader.nextDouble();
System.out.print("输入边b:");
b=reader.nextDouble();
System.out.print("输入边c:");
c=reader.nextDouble();
if(a+b>c&&a+c>b&&b+c>a){
if(a*a==b*b+c*c||b*b==a*a+c*c||c*c==a*a+b*b){
System.out.printf("%-8.3f%-8.3f%-8.3f构成直角三角形",a,b,c);
}
else if(a*a<b*b+c*c&&b*b<a*a+c*c&&c*c<a*a+b*b){
System.out.printf("%-8.3f%-8.3f%-8.3f构成锐角三角形",a,b,c);
}
else
System.out.printf("%-8.3f%-8.3f%-8.3f构成钝角三角形",a,b,c);
}
else
System.out.printf("%-8.3f%-8.3f%-8.3f不能构成三角形",a,b,c);
}
}
import java.util.*;
public class Example3_4 {
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
System.out.println("输入一个月份:");
int n=reader.nextInt();
switch(n){
case 1:
case 2:
case 3:System.out.printf("%d月属于第一季度",n);
break;
case 4:
case 5:
case 6:System.out.printf("%d月属于第二季度",n);
break;
case 7:
case 8:
case 9:System.out.printf("%d月属于第三季度",n);
break;
case 10:
case 11:
case 12:System.out.printf("%d月属于第四季度",n);
break;
default:System.out.printf("%d不代表月份",n);
}
}
}
public class Example3_5 {
public static void main(String args[]){
double sum=0,item=1;
int i=1;
while(i<=1000){
sum+=item;
i++;
item*=(1.0/i);
}
sum+=1;
System.out.println("e="+sum);
sum=0;i=1;
item=1;
do{
sum+=item;
i++;
item*=(1.0/i);
} while(i<=1000);
sum+=1;
System.out.println("e="+sum);
}
}
public class Example3_6 {
public static void main(String args[]){
int sum,i,j;
for(i=1;i<=1000;i++){
for(j=1,sum=0;j<=i/2;j++){
if(i%j==0){
sum+=j;
}
}
if(sum==i)
System.out.printf("%8d是一个完数\n",i);
}
}
}
import java.util.*;
public class Example3_8 {
public static void main(String args[]){
int n,start,end,middle;
int a[]={-2,1,4,5,8,12,17,23,45,56,90,100};
start=0;
end=a.length;
middle=(start+end)/2;
int count=0;
Scanner reader=new Scanner(System.in);
System.out.print("请输入一个整数:");
n=reader.nextInt();
while(n!=a[middle]){
if(n>a[middle]) start=middle;
else if(n<a[middle]){
end=middle;
}
middle=(start+end)/2;
count++;
if(count>a.length/2)
break;
}
if(count>a.length/2)
System.out.println(n+"不在数组中");
else
System.out.println(n+"时数组中第"+middle+"个元素");
}
}